以前,Promise库有promise,Q,bluebird等,后来,ES6中也新增了原生Promise。
Promiss/A+规范 https://promisesaplus.com/
An open standard for sound, interoperable JavaScript promises—by implementers, for implementers.
一个健全的通用JavaScript Promise开放标准,源于开发者,并归于开发者
function test(resolve, reject) { var time = Math.random(); if(time > 0.5){ resolve('resolve'+time); }else{ reject('reject'+time); } } var p1 = new Promise(test); var p2 = p1.then(function(r){ console.log(r); }); var p3 = p2.catch(function(res){ console.log(res); }); // 0.5秒后返回input*input的计算结果: function multiply(input) { return new Promise(function (resolve, reject) { console.log('calculating ' + input + ' x ' + input + '...'); setTimeout(resolve, 100, input * input); }); } // 0.5秒后返回input+input的计算结果: function add(input) { return new Promise(function (resolve, reject) { console.log('calculating ' + input + ' + ' + input + '...'); setTimeout(resolve, 100, input + input); }); } var p = new Promise(function (resolve, reject) { console.log('start new Promise...'); resolve(123); }); p.then(multiply) .then(add) .then(multiply) .then(add) .then(function (result) { console.log('Got value: ' + result); }).catch(function(reason){ console.log('catch...'+reason); });
相关教程:
https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014345008539155e93fc16046d4bb7854943814c4f9dc2000
http://liubin.org/promises-book/
http://www.jianshu.com/p/473cd754311f
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。