promise的执行流程
promise串行执行异步
job1.then(job2).then(job3).catch(handleError);
// 0.5秒后返回input*input的计算结果:
function multiply(input) {
return new Promise(function (resolve, reject) {
console.log('calculating ' + input + ' x ' + input + '...');
setTimeout(resolve, 500, input * input);
});
}
// 0.5秒后返回input+input的计算结果:
function add(input) {
return new Promise(function (resolve, reject) {
console.log('calculating ' + input + ' + ' + input + '...');
setTimeout(resolve, 500, 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);
});
promise并行执行异步任务(Promise.all()
)
- 假设此时有任务A和任务B两个异步任务,两个任务全部执行完成之后执行任务C,此时可以使用Promise.all()实现
var p1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(resolve, 600, 'P2');
});
var p3=function(res){
console.log(res)
}
Promise.all([p1, p2]).then(p3);
promise并行执行多个任务,但是只需要得到先返回的结果即可(Promise.race()
)
- 假设此时有任务A和任务B两个异步任务,两个任务任意一个完成之后执行任务C,此时可以使用Promise.race()实现
var p1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(resolve, 600, 'P2');
});
var p3=function(res){
console.log(res)
}
Promise.race([p1, p2]).then(p3);