【发布时间】:2018-12-16 19:25:52
【问题描述】:
我的问题:从 Promise 对象中分离处理是否安全?
如果我这样做......
var promise1 = new Promise(function(resolve, reject) {
var json = { "counter":0 }
console.log('execute now, worry later ...')
json.counter++;
console.log(json.counter)
resolve(json);
});
var then = function() {
promise1.then(function(value) { console.log('value: '+value.counter) });
}
setTimeout(then, 3000);
var promise2 = new Promise(function(resolve, reject) {
console.log('error thrown here ...')
throw new Error('will it behave the same as with then?');
});
var catchFunc = function() {
promise2.then().catch(function(error) { console.log('error: '+error.message) });
}
setTimeout(catchFunc, 3000);
然后我得到有意义的警告......
execute now, worry later ...
1
error thrown here ...
(node:9748) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: will it behave the same as with then?
(node:9748) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
value: 1
error: will it behave the same as with then?
背景:在某些情况下,我希望我的承诺同时运行。在某些情况下,我希望它们按顺序运行。我发现的最简单的实现是将两个变体包装到一个函数中,将其推送到 map 中,然后在 reduce 中处理“then/catch”。结果是我在第一个变体中的处理(同时)是在包装和分离时,如我上面的示例所示。
如果它是安全的,我怎样才能从我的日志中删除警告?
【问题讨论】:
-
嗨 Amadan,我认为您的评论是摆脱警告的建议。捕捉没有 then 并没有什么不同。
-
看错了,抱歉。问题不在于它们在代码上是分开的,而是它们在时间上是分开的。您能否展示一个需要异步附加错误处理程序的真实情况?
-
这是顺序运行异步操作的错误方式。你应该链接承诺
fn().then(op1).then(op2)。那么,你就没有这些问题了。 -
这里真正的问题是什么?如果您只是尝试按顺序运行多个异步操作(因此一个在下一个开始之前完成),请编辑您的问题以直接说明。
-
我想知道谁对我投了反对票。唯一的原因可能是我错过了 Estus 的帖子。我的问题显示了研究工作,有用且清晰。埃斯图斯回答了这个问题,他的回答正是我的目标。其他人可能会受益。