JavaScript 承诺链

示例

then承诺的方法会返回新的承诺。

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

promise
    // 5秒后
    .then(() => 2)
    // 从then回调返回值将导致
    // 以此价值解决的新承诺
    .then(value => { /* value === 2 */ });

Promise从then回调返回a会将其追加到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允许拒绝承诺恢复,类似于如何catch在try/catch语句的工作。then在a之后链接的任何对象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,则末尾的a将捕获链中的任何拒绝:

p.catch(() => Promise.reject('oh yes'))
  .then(console.log.bind(console))      // 不会被叫
  .catch(console.error.bind(console));  // outputs "oh yes"

在某些情况下,您可能希望“分支”功能的执行。您可以通过根据条件从函数返回不同的promise来做到这一点。在代码的后面,您可以将所有这些分支合并为一个,以调用它们上的其他函数和/或在一个地方处理所有错误。

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会在可能发生的任何分支上获取错误。