有没有办法回报对.catch和.then的承诺

Is there a way to return a promise to .catch and .then

本文关键字:then 承诺 catch 回报 有没有      更新时间:2023-09-26

基本上,无论代码是否抛出错误,我都想运行相同的代码。现在我在做这个:

.then((resp) => {
    assert(false);
}, err => {
    assert.equal(2, err.error.errors.length);
    });
});

但我想做这样的事情:

.something((resp, err) => {
    assert.equal(400, resp.statusCode)
    assert.equal(2, err.error.errors.length);
}

可以

只需使用catch并从中返回一些内容,然后在承诺上使用then .catch返回:

thePromise
    .catch(err => err)
    .then(resultOrError => {
        // Your code
    });

如果promise已被解析,则then回调接收的参数(上面的resultOrError)将是已解析的值,如果promise被拒绝,则是被拒绝的值(松散地说,"error")。如果你想区分它们,你自然可以在catch中做更多的事情。

示例(运行几次,你会看到它得到解决,也被拒绝):

let p = new Promise((resolve, reject) => {
  setTimeout(() => {
    if (Math.random() < 0.5) {
      resolve("success");
    } else {
      reject("error");
    }
  }, 0);
});
p.catch(err => err).then(resultOrError => {
  console.log("Got this:", resultOrError);
});

。。。但是交替地

在使用解析的值或拒绝的值之后,您可以有一个通用的函数both回调调用:

function doSomethingNoMatterWhat() {
    // ...
}
thePromise
    .then(result => {
        // Presumably use `result`, then:
        doSomethingNoMatterWhat();
    })
    .catch(error => {
        // Presumably use `error`, then:
        doSomethingNoMatterWhat();
    });