javascript - 如果序列中的一个 Promise 抛出错误,则按顺序解析 Promise 并中断该序列
问题描述
假设我async
设置了三个功能,如下所示:
const stepOne = async () => { setTimeout(function() {
console.log("step 1")
}, 3000) }
const stepTwo = async () => { throw new Error("Error at step two") }
const stepThree = async () => { console.log("step 3") }
我将如何按顺序执行所有这些函数并在 stepTwo 中断承诺链,不允许 stepThree 函数运行?
所以,
正常顺序是这样的:stepOne --> stepTwo --> stepThree
在 stepTwo 引发错误的序列:stepOne --> stepTwo
stepTwo 抛出的错误需要在 end catch 块中捕获。
更新#1:错过了问题的关键要素。await 不能使用,因为这三个函数需要在非异步函数中调用。
例子:
const testFunc = () => {
resolve three promises
sequentially, break the promise chain when error is thrown
and ultimately, catch errors here
}
解决方案
如果您要解决承诺,您的代码将起作用,stepOne
因为setTimeout
只是将函数添加到堆栈中并且不等待它解决。
如果您将返回一个 PromisestepOne
并在之后解决它,console.log
那么try catch
将等待stepOne
并捕获错误stepTwo
这是您的代码示例
const stepOne = async () => {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log("step 1")
resolve(true);
}, 3000)
});
}
const stepTwo = async () => { throw new Error("Error at step two") }
const stepThree = async () => {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log("step 3")
resolve(true);
}, 3000)
});
}
(() => {
stepOne()
.then(stepTwo)
.then(stepThree)
.catch(error => {
console.log(error);
})
})();
现在console.log
看起来像这样
step 1
Error: Error at step two
at stepTwo (/home/user/develop/test/stackoverflow.js:10:38)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
推荐阅读
- python - 如何通过 Python 中的 BeautifulSoup 提取子标签中的 href?
- signalr.client - SignalR .Net 客户端无法与 https 连接
- c# - 如何填充队列并同时打印?
- python - 尝试使用 pip 命令时安装 python 后出现语法错误
- python - Python简单不在语句中不起作用
- python - 获取条形图matplotlib的平均值/标准差
- sql - 根据 BigQuery 中的先前行计算
- java-8 - 我可以使用java流api按值对象中的字段对映射进行分组,然后创建一个新映射,其中字段作为键,原始键作为值
- powershell - 脚本成功更改目录中所有文件的时间戳。但是子目录文件保持不变。需要什么改变?
- c# - 为什么 asp.net 5 剃须刀页面中没有开发人员异常页面?