标签:任务 处理 错误 cti set 输出 resolve rac ISE
- 在异步执行的流程中,把执行代码和处理结果的代码清晰地分离(因为Promise对象有链式写法,有then和catch)
- 组合使用Promise,就可以把很多异步任务以并行和串行的方式组合起来执行。
‘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);
});
job1.then(job2).then(job3).catch(handleError);
其中,job1、job2和job3都是Promise对象。
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‘]
});
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‘
});
标签:任务 处理 错误 cti set 输出 resolve rac ISE
原文地址:https://www.cnblogs.com/allen2333/p/8979550.html