避免忘记承诺 returns
Avoid forgotten promise returns
当我使用 promises 来表达作业之间的依赖关系时,解析值变得不重要时,我可能会在某处忘记 return 。示例:
startSomething().then(function() {
Q.all(tasks.map(function(task) { return task.startIt(); }))
}).then(collectOutput).done();
这里 Q.all
return 是一个承诺,我应该 return 编辑它。不这样做意味着在 collectOutput
被调用时,所有任务都已启动,但不能保证它们已完成。
这种错误会导致竞争条件,并且可能极难重现和追踪。所以我想知道,是否有一些工具可以帮助检测和避免此类问题?也许某些 promise 库会在 return 未定义函数时发出警告?或者检测没有听众的承诺,Bluebird 处理未处理的拒绝的方式?
实际上,如果您在处理程序中创建了承诺但没有 return,bluebird 会警告您。如果你愿意掉Q.
这里还有一个in-depth explanation about bluebird's warnings
Warning: a promise was created in a handler but none were returned from it This usually means that you simply forgot a return statement
somewhere which will cause a runaway promise that is not connected to
any promise chain.
For example:
getUser().then(function(user) {
getUserData(user);
}).then(function(userData) {
// userData is undefined
});
当我使用 promises 来表达作业之间的依赖关系时,解析值变得不重要时,我可能会在某处忘记 return 。示例:
startSomething().then(function() {
Q.all(tasks.map(function(task) { return task.startIt(); }))
}).then(collectOutput).done();
这里 Q.all
return 是一个承诺,我应该 return 编辑它。不这样做意味着在 collectOutput
被调用时,所有任务都已启动,但不能保证它们已完成。
这种错误会导致竞争条件,并且可能极难重现和追踪。所以我想知道,是否有一些工具可以帮助检测和避免此类问题?也许某些 promise 库会在 return 未定义函数时发出警告?或者检测没有听众的承诺,Bluebird 处理未处理的拒绝的方式?
实际上,如果您在处理程序中创建了承诺但没有 return,bluebird 会警告您。如果你愿意掉Q.
这里还有一个in-depth explanation about bluebird's warnings
Warning: a promise was created in a handler but none were returned from it This usually means that you simply forgot a return statement
somewhere which will cause a runaway promise that is not connected to any promise chain.
For example:
getUser().then(function(user) { getUserData(user); }).then(function(userData) { // userData is undefined });