ES6中的Promise对象
var p = new Promise(function(resolve, reject){ window.setTimeout(function(){ console.log("1",1); resolve(1); },10); }); p.then(function(a){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log("2",a+1); resolve(a + 1); },10); }); }).then(function(a){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log("3",a+1); resolve(a + 1); },10); }); }).then((a)=>new Promise((resolve,reject)=>{ window.setTimeout(function(){ console.log("52222",a+1); resolve(a + 1); },10); }));
for循环中的ajax请求依次执行,而不是无序执行。
(function () { var ajax = function(callback){ window.setTimeout(function(){ callback(new Date()); },1000); }; var promiseAjax = function(num){ return function (pre){ return new Promise(function (resolve, reject) { ajax(function (d) { console.log(num,d); resolve(d); }); }); } } ; var p = promiseAjax(-1)(); for (var i = 0; i < 10; i++) { p = p.then(promiseAjax(i)); } })();
Angular中的$q对象
var $q = {}; var deferred = $q.defer(); var promise = deferred.promise; promise.then(function(a){ return a + "222" }).then(function(a){ var deferred = $q.defer(); window.setTimeout(function(){ deferred.resolve("333"); },100); return deferred.promise; }); deferred.resolve("1111");
var deferred = $q.defer() ...(and then from console inspection)... $q: Object {defer: function, reject: function, when: function, all: function} deferred: Object {resolve: function, reject: function, notify: function, promise: Object} deferred.promise: Object {then: function, catch: function, finally: function}
$q.reject(reason) returns a rejected promise with the reason passed as argument and defered. Reject rejects an existent defered whether its process has finished or not.