有没有办法回报对.catch和.then的承诺
Is there a way to return a promise to .catch and .then
基本上,无论代码是否抛出错误,我都想运行相同的代码。现在我在做这个:
.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();
});
相关文章:
- AngularJS因果报应测试规范承诺未解析,且未调用.then()
- 当链接javascript承诺时,如何处理then()函数中的条件
- 角承诺的“then”函数的成功回调的词汇范围是什么?
- “未捕获(在承诺中)”在获取“then”方法中调用拒绝函数时
- 为什么.then()在承诺真正解决之前就被解雇了
- Javascript承诺:then()'s是't同步
- Chain承诺使用then()
- Javascript 承诺 .catch 仍然调用 final variable.then
- 当承诺在监视函数中解析时,如何使承诺的 then 函数起作用
- 链接承诺而不使用“then”
- 问.js节点承诺.“套接字”上缺少错误处理程序.类型错误:无法调用未定义的方法“then”
- 为什么 .then() 不等待承诺
- 咖啡脚本中的承诺.尝试将多个参数传递给“then”时出现“意外逗号”错误
- 在 then() 中断开 for 循环 在一个承诺
- 然后 .then() 函数似乎在承诺完成之前运行
- 用一个参数承诺 .then()
- 与茉莉花中 ES6 承诺的 then/catch 方法同步
- 承诺链接:在next-then回调中使用上一个承诺的结果
- AngularJs的承诺&;then &;承诺之前的火焰已被化解
- 如何重用一个函数,是在一个链之间的then(承诺相关)