JavaScript promise 链,并行promise

Promise 链

promise 的 then 方法返回一个新的 promise:

const promise = new Promise(resolve => setTimeout(resolve, 5000));

promise
    // 5 seconds later
    .then(() => 2)
    // returning a value from a then callback will cause
    // the new promise to resolve with this value
    .then(value => { /* value === 2 */ });

从 then 返回的 promise 将会粘到 promise 链上:

function wait(millis) {
    return new Promise(resolve => setTimeout(resolve, millis));
}

const p = wait(5000).then(() => wait(4000)).then(() => wait(1000));
p.then(() => { /* 10 seconds have passed */ });

catch 允许恢复一个 rejected 的 promise,类似try/catch中的catch。在 promise 链中的 then,如果在catch 之后,将会用catch中的结果值执行其错误处理代码。

const p = new Promise(resolve => {throw 'oh no'});
p.catch(() => 'oh yes').then(console.log.bind(console));  // outputs "oh yes"

如果在链中没有 catch 或者 reject 处理器, 末尾的 catch 将捕捉链中任何的rejection。

p.catch(() => Promise.reject('oh yes'))
  .then(console.log.bind(console))      // won't be called
  .catch(console.error.bind(console));  // outputs "oh yes"

某种情况下你可能想把拆分函数的执行,你可以通过根据不同的条件返回不同的 promises 来实现。后面在代码中再合并多个函数分开执行的结果:

promise
    .then(result => {          
        if (result.condition) {
            return handlerFn1() 
                .then(handlerFn2);
        } else if (result.condition2) {
            return handlerFn3()
                .then(handlerFn4);
        } else {
            throw new Error("Invalid result");
        }
    })
    .then(handlerFn5)
    .catch(err => {
        console.error(err);
    });

执行顺序就像这样:

promise --> handlerFn1 -> handlerFn2 --> handlerFn5 ~~> .catch()
         |                            ^
         V                            |
         -> handlerFn3 -> handlerFn4 -^            

一个 catch 就能捕捉分支上可能产生的错误了。

并行 promises

Promise.all() 静态方法接受一个可遍历的 promises列表,并返回一个新的 promise,这样就解决了当所有promises都解决了时,或有任何其中一个被rejected了时:

// wait "millis" ms, then resolve with "value"
function resolve(millis, value) {
    return new Promise(resolve => setTimeout(() => resolve(value), millis));
}

// wait "millis" ms, then reject with "reason"
function reject(millis, reason) {
    return new Promise((_, reject) => setTimeout(() => reject(reason), millis));
}

Promise.all([
    resolve(5000, 1),
    resolve(6000, 2),
    resolve(7000, 3)    
]).then(values => console.log(values)); // outputs "[1, 2, 3]" after 7 seconds.

Promise.all([
    resolve(5000, 1),
    reject(6000, 'Error!'),
    resolve(7000, 2)
]).then(values => console.log(values)) // does not output anything
.catch(reason => console.log(reason)); // outputs "Error!" after 6 seconds

而非 promise 的值是 “promisified”

Promise.all([
    resolve(5000, 1),
    resolve(6000, 2),
    { hello: 3 }
])
.then(values => console.log(values)); // outputs "[1, 2, { hello: 3 }]" after 6 seconds

分解赋值可以帮助从多个promises中取值:

Promise.all([
    resolve(5000, 1),
    resolve(6000, 2),
    resolve(7000, 3)
])
.then(([result1, result2, result3]) => {
    console.log(result1);
    console.log(result2);
    console.log(result3);
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值