JavaScript - Promise对象
优点:
- 在异步执行的流程中,把执行代码和处理结果的代码清晰地分离(因为Promise对象有链式写法,有then和catch)
- 组合使用Promise,就可以把很多异步任务以并行和串行的方式组合起来执行。
例子1. 生成一个0-2之间的随机数,如果小于1,则等待一段时间后返回成功,否则返回失败:
'use strict';
// 清除log:
var logging = document.getElementById('test-promise-log');
while (logging.children.length > 1) {
logging.removeChild(logging.children[logging.children.length - 1]);
}
// 输出log到页面:
function log(s) {
var p = document.createElement('p');
p.innerHTML = s;
logging.appendChild(p);
}
new Promise(function (resolve, reject) {
log('start new Promise...');
var timeOut = Math.random() * 2;
log('set timeout to: ' + timeOut + ' seconds.');
setTimeout(function () {
if (timeOut < 1) {
log('call resolve()...');
resolve('200 OK');
}
else {
log('call reject()...');
reject('timeout in ' + timeOut + ' seconds.');
}
}, timeOut * 1000);
}).then(function (r) {
log('Done: ' + r);
}).catch(function (reason) {
log('Failed: ' + reason);
});
例子2. 串行执行若干个异步任务,需要先做任务1,如果成功后再做任务2,以此类推,任何任务失败则不再继续并执行错误处理函数。(链式写法)
job1.then(job2).then(job3).catch(handleError);
其中,job1、job2和job3都是Promise对象。
例子3. 并行执行,同时执行p1和p2,并在它们都完成后执行then:
var p1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(resolve, 600, 'P2');
});
// 同时执行p1和p2,并在它们都完成后执行then:
Promise.all([p1, p2]).then(function (results) {
console.log(results); // 获得一个Array: ['P1', 'P2']
});
例子4. 并行执行,获得先返回的结果即可
var p1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(resolve, 600, 'P2');
});
Promise.race([p1, p2]).then(function (result) {
console.log(result); // 'P1'
});