PromiseJs
(function() {
var define, requireModule, require, requirejs; (function() {
var registry = {},
seen = {}; define = function(name, deps, callback) {
registry[name] = {
deps: deps,
callback: callback
};
}; requirejs = require = requireModule = function(name) {
requirejs._eak_seen = registry; if (seen[name]) {
return seen[name];
}
seen[name] = {}; if (!registry[name]) {
throw new Error("Could not find module " + name);
} var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports; for (var i = 0,
l = deps.length; i < l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
} var value = callback.apply(this, reified);
return seen[name] = exports || value; function resolve(child) {
if (child.charAt(0) !== '.') {
return child;
}
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1); for (var i = 0,
l = parts.length; i < l; i++) {
var part = parts[i]; if (part === '..') {
parentBase.pop();
} else if (part === '.') {
continue;
} else {
parentBase.push(part);
}
} return parentBase.join("/");
}
};
})(); define("promise/all", ["./utils", "exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */ var isArray = __dependency1__.isArray;
var isFunction = __dependency1__.isFunction; /**
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The return promise
is fulfilled with an array that gives all the values in the order they were
passed in the `promises` array argument. Example: ```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.resolve(2);
var promise3 = RSVP.resolve(3);
var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
``` If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example: Example: ```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.reject(new Error("2"));
var promise3 = RSVP.reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
``` @method all
@for RSVP
@param {Array} promises
@param {String} label
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
*/
function all(promises) {
/*jshint validthis:true */
var Promise = this; if (!isArray(promises)) {
throw new TypeError('You must pass an array to all.');
} return new Promise(function(resolve, reject) {
var results = [],
remaining = promises.length,
promise; if (remaining === 0) {
resolve([]);
} function resolver(index) {
return function(value) {
resolveAll(index, value);
};
} function resolveAll(index, value) {
results[index] = value;
if (--remaining === 0) {
resolve(results);
}
} for (var i = 0; i < promises.length; i++) {
promise = promises[i]; if (promise && isFunction(promise.then)) {
promise.then(resolver(i), reject);
} else {
resolveAll(i, promise);
}
}
});
} __exports__.all = all;
});
define("promise/asap", ["exports"],
function(__exports__) {
"use strict";
var browserGlobal = (typeof window !== 'undefined') ? window: {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var local = (typeof global !== 'undefined') ? global: this; // node
function useNextTick() {
return function() {
process.nextTick(flush);
};
} function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {
characterData: true
}); return function() {
node.data = (iterations = ++iterations % 2);
};
} function useSetTimeout() {
return function() {
local.setTimeout(flush, 1);
};
} var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0],
arg = tuple[1];
callback(arg);
}
queue = [];
} var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
} function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
// If length is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush();
}
} __exports__.asap = asap;
});
define("promise/cast", ["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.Promise.cast` returns the same promise if that promise shares a constructor
with the promise being casted. Example: ```javascript
var promise = RSVP.resolve(1);
var casted = RSVP.Promise.cast(promise); console.log(promise === casted); // true
``` In the case of a promise whose constructor does not match, it is assimilated.
The resulting promise will fulfill or reject based on the outcome of the
promise being casted. In the case of a non-promise, a promise which will fulfill with that value is
returned. Example: ```javascript
var value = 1; // could be a number, boolean, string, undefined...
var casted = RSVP.Promise.cast(value); console.log(value === casted); // false
console.log(casted instanceof RSVP.Promise) // true casted.then(function(val) {
val === value // => true
});
``` `RSVP.Promise.cast` is similar to `RSVP.resolve`, but `RSVP.Promise.cast` differs in the
following ways:
* `RSVP.Promise.cast` serves as a memory-efficient way of getting a promise, when you
have something that could either be a promise or a value. RSVP.resolve
will have the same effect but will create a new promise wrapper if the
argument is a promise.
* `RSVP.Promise.cast` is a way of casting incoming thenables or promise subclasses to
promises of the exact class specified, so that the resulting object's `then` is
ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise). @method cast
@for RSVP
@param {Object} object to be casted
@return {Promise} promise that is fulfilled when all properties of `promises`
have been fulfilled, or rejected if any of them become rejected.
*/ function cast(object) {
/*jshint validthis:true */
if (object && typeof object === 'object' && object.constructor === this) {
return object;
} var Promise = this; return new Promise(function(resolve) {
resolve(object);
});
} __exports__.cast = cast;
});
define("promise/config", ["exports"],
function(__exports__) {
"use strict";
var config = {
instrument: false
}; function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
} __exports__.config = config;
__exports__.configure = configure;
});
define("promise/polyfill", ["./promise", "./utils", "exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var RSVPPromise = __dependency1__.Promise;
var isFunction = __dependency2__.isFunction; function polyfill() {
var es6PromiseSupport = "Promise" in window &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"cast" in window.Promise && "resolve" in window.Promise && "reject" in window.Promise && "all" in window.Promise && "race" in window.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new window.Promise(function(r) {
resolve = r;
});
return isFunction(resolve);
} ()); if (!es6PromiseSupport) {
window.Promise = RSVPPromise;
}
} __exports__.polyfill = polyfill;
});
define("promise/promise", ["./config", "./utils", "./cast", "./all", "./race", "./resolve", "./reject", "./asap", "exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __exports__) {
"use strict";
var config = __dependency1__.config;
var configure = __dependency1__.configure;
var objectOrFunction = __dependency2__.objectOrFunction;
var isFunction = __dependency2__.isFunction;
var now = __dependency2__.now;
var cast = __dependency3__.cast;
var all = __dependency4__.all;
var race = __dependency5__.race;
var staticResolve = __dependency6__.resolve;
var staticReject = __dependency7__.reject;
var asap = __dependency8__.asap; var counter = 0; config.async = asap; // default async is asap;
function Promise(resolver) {
if (!isFunction(resolver)) {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
} if (! (this instanceof Promise)) {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
} this._subscribers = []; invokeResolver(resolver, this);
} function invokeResolver(resolver, promise) {
function resolvePromise(value) {
resolve(promise, value);
} function rejectPromise(reason) {
reject(promise, reason);
} try {
resolver(resolvePromise, rejectPromise);
} catch(e) {
rejectPromise(e);
}
} function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value,
error,
succeeded,
failed; if (hasCallback) {
try {
value = callback(detail);
succeeded = true;
} catch(e) {
failed = true;
error = e;
}
} else {
value = detail;
succeeded = true;
} if (handleThenable(promise, value)) {
return;
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
resolve(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
} var PENDING = void 0;
var SEALED = 0;
var FULFILLED = 1;
var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length; subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
} function publish(promise, settled) {
var child, callback, subscribers = promise._subscribers,
detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail);
} promise._subscribers = null;
} Promise.prototype = {
constructor: Promise, _state: undefined,
_detail: undefined,
_subscribers: undefined, then: function(onFulfillment, onRejection) {
var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) {
var callbacks = arguments;
config.async(function invokePromiseCallback() {
invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
});
} else {
subscribe(this, thenPromise, onFulfillment, onRejection);
} return thenPromise;
}, 'catch': function(onRejection) {
return this.then(null, onRejection);
}
}; Promise.all = all;
Promise.cast = cast;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject; function handleThenable(promise, value) {
var then = null,
resolved; try {
if (promise === value) {
throw new TypeError("A promises callback cannot return that same promise.");
} if (objectOrFunction(value)) {
then = value.then; if (isFunction(then)) {
then.call(value,
function(val) {
if (resolved) {
return true;
}
resolved = true; if (value !== val) {
resolve(promise, val);
} else {
fulfill(promise, val);
}
},
function(val) {
if (resolved) {
return true;
}
resolved = true; reject(promise, val);
}); return true;
}
}
} catch(error) {
if (resolved) {
return true;
}
reject(promise, error);
return true;
} return false;
} function resolve(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (!handleThenable(promise, value)) {
fulfill(promise, value);
}
} function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._state = SEALED;
promise._detail = value; config.async(publishFulfillment, promise);
} function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = SEALED;
promise._detail = reason; config.async(publishRejection, promise);
} function publishFulfillment(promise) {
publish(promise, promise._state = FULFILLED);
} function publishRejection(promise) {
publish(promise, promise._state = REJECTED);
} __exports__.Promise = Promise;
});
define("promise/race", ["./utils", "exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray; /**
`RSVP.race` allows you to watch a series of promises and act as soon as the
first promise given to the `promises` argument fulfills or rejects. Example: ```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
}); var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 2");
}, 100);
}); RSVP.race([promise1, promise2]).then(function(result){
// result === "promise 2" because it was resolved before promise1
// was resolved.
});
``` `RSVP.race` is deterministic in that only the state of the first completed
promise matters. For example, even if other promises given to the `promises`
array argument are resolved, but the first completed promise has become
rejected before the other promises became fulfilled, the returned promise
will become rejected: ```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
}); var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error("promise 2"));
}, 100);
}); RSVP.race([promise1, promise2]).then(function(result){
// Code here never runs because there are rejected promises!
}, function(reason){
// reason.message === "promise2" because promise 2 became rejected before
// promise 1 became fulfilled
});
``` @method race
@for RSVP
@param {Array} promises array of promises to observe
@param {String} label optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise that becomes fulfilled with the value the first
completed promises is resolved with if the first completed promise was
fulfilled, or rejected with the reason that the first completed promise
was rejected with.
*/
function race(promises) {
/*jshint validthis:true */
var Promise = this; if (!isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve, reject) {
var results = [],
promise; for (var i = 0; i < promises.length; i++) {
promise = promises[i]; if (promise && typeof promise.then === 'function') {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
});
} __exports__.race = race;
});
define("promise/reject", ["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.reject` returns a promise that will become rejected with the passed
`reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript
var promise = new RSVP.Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
}); promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
``` Instead of writing the above, your code now simply becomes the following: ```javascript
var promise = RSVP.reject(new Error('WHOOPS')); promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
``` @method reject
@for RSVP
@param {Any} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become rejected with the given
`reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Promise = this; return new Promise(function(resolve, reject) {
reject(reason);
});
} __exports__.reject = reject;
});
define("promise/resolve", ["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.resolve` returns a promise that will become fulfilled with the passed
`value`. `RSVP.resolve` is essentially shorthand for the following: ```javascript
var promise = new RSVP.Promise(function(resolve, reject){
resolve(1);
}); promise.then(function(value){
// value === 1
});
``` Instead of writing the above, your code now simply becomes the following: ```javascript
var promise = RSVP.resolve(1); promise.then(function(value){
// value === 1
});
``` @method resolve
@for RSVP
@param {Any} value value that the returned promise will be resolved with
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve(value) {
/*jshint validthis:true */
var Promise = this;
return new Promise(function(resolve, reject) {
resolve(value);
});
} __exports__.resolve = resolve;
});
define("promise/utils", ["exports"],
function(__exports__) {
"use strict";
function objectOrFunction(x) {
return isFunction(x) || (typeof x === "object" && x !== null);
} function isFunction(x) {
return typeof x === "function";
} function isArray(x) {
return Object.prototype.toString.call(x) === "[object Array]";
} // Date.now is not available in browsers < IE9
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
var now = Date.now ||
function() {
return new Date().getTime();
}; __exports__.objectOrFunction = objectOrFunction;
__exports__.isFunction = isFunction;
__exports__.isArray = isArray;
__exports__.now = now;
});
requireModule('promise/polyfill').polyfill();
} ());
下载地址:
http://s3.amazonaws.com/es6-promises/promise-0.1.1.js
http://s3.amazonaws.com/es6-promises/promise-0.1.1.min.js
PromiseJs的更多相关文章
- Promise-js中的同步和异步
js中的同步和异步 自从读了研后,走上了学术之路,每天除了看论文就是做实验,最后发现自己还是喜欢开发呀,于是我又重回前端啦~ 隔了这么久没学前端,好像很多东西都忘了不少,而且不得不说前端的技术更新 ...
- Promise-js异步加载解决方案
范例: var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log('执行完 ...
- Promise deeply lookup
Motivation Consider the following synchronous JavaScript function to read a file and parse it as JSO ...
- Javascript Promise入门
是什么? https://www.promisejs.org/ What is a promise? The core idea behind promises is that a promise r ...
- JS魔法堂:剖析源码理解Promises/A规范
一.前言 Promises/A是由CommonJS组织制定的异步模式编程规范,有不少库已根据该规范及后来经改进的Promises/A+规范提供了实现 如Q, Bluebird, when, rsvp. ...
- 一个简单的Promise 实现
用了这么长时间的promise,也看了很多关于promise 的文章博客,对promise 算是些了解.但是要更深的理解promise,最好的办法还是自己实现一个. 我大概清楚promise 是对异步 ...
- (翻译)异步编程之Promise(1):初见魅力
原文:https://www.promisejs.org/ by Forbes Lindesay 异步编程系列教程: (翻译)异步编程之Promise(1)--初见魅力 异步编程之Promise(2) ...
- 【JavaScript】JavaScript Promise 探微
http://www.html-js.com/article/Promise-translation-JavaScript-Promise-devil-details 原文链接:JavaScript ...
- 实现nodejs的promises库(基于promise.js改写)
原promise.js库地址:https://github.com/stackp/promisejs promises是JavaScript实现优雅编程的一个非常不错的轻量级框架.该框架可以让你从杂乱 ...
随机推荐
- spring(13)------全面深入解析spring的AOP
一,AOP的基本思想 AOP(Aspect Oriented Programming)翻译成中文的大意是面向切面编程,主要目的解决让不该牵扯在一起的代码分离开来. (1)认识AOP 应用程序中通常包含 ...
- shutil 模块 高级的文件、文件夹、压缩包 处理模块
高级的文件.文件夹.压缩包 处理模块 # 将文件内容拷贝到另一个文件中 shutil.copyfileobj(fsrc, fdst[, length]) import shutil shutil.co ...
- java.sql.SQLException: The user specified as a definer ('root'@'%') does not exist
权限问题,授权给 root 所有sql 权限 在Navicat for MySQL中按F6进入命令列界面 mysql> grant all privileges on *.* to root@& ...
- Vuex核心知识(转)
转:http://www.cnblogs.com/ghost-xyx/p/6380689.html Vuex 是一个专门为 Vue.js 应该程序开发的状态管理模式,它类似于 Redux 应用于 Re ...
- Python基础之socket编程(Day29)
一.客户端/服务器架构 1.硬件c/s架构(打印机) 2.软件c/s架构 互联网中处处是c/s架构 浏览的网页就是如此 C/S架构与socket的关系 socket就是为了完成c/s架构的开发 二.s ...
- Ubuntu 安装VMware Tools
安装步骤: 首先,点击VMware菜单的-VM-Install VMware Tools (虚拟机-装载VMwareTool 工具) 这时,在Ubuntu下会自动加载Linux版的VMware Too ...
- iOS copy 和 mutableCopy 学习
(参考 iOS 52个技巧学习心得笔记 第二章 对象 , 消息, 运行期)的对象部分 关于Copy 有个经典问题”大部分的时候NSString的属性都是copy,那copy与strong的情况下到底 ...
- 面对 to B 业务该如何构建研发管理体系?
未来离我们越来越近,而过去并未走远,我们发现科技公司2B业务兴起,腾讯认为互联网下半场属于产业互联网,需要进行一次重要的战略升级.它们在国庆节最后一天进行新一轮组织架构调整,最亮眼的就是新成立云与智慧 ...
- $SublimeText2常用快捷键
1.删除一行:ctrl + shift + K2.替换:ctrl + H3.设置书签:Ctrl+F2设置书签F2 下一个书签Shift+F2上一个书签4.查找:ctrl + F 查找F3 查找下一个s ...
- hadoop04---shell
Linux上的mysql安装之后卸载是卸载不干净的,ping服务器ping不通就是把icmp协议关闭了,ping使用的是icmp协议. Export是全局变量,所有用户登录进来都可以使用. 1.ipt ...