以下 JavaScript 函数来自 You Don't Know JS: Async & Performance 。根据我的理解,第一条评论 //start do things that might take a while
具有误导性。实际可能异步完成某些操作的代码部分位于传递到 Promise 的函数中。构造函数。
function foo(x) {
// start doing something that could take a while *misleading comment*
// construct and return a promise
return new Promise( /* executor */ function(resolve,reject){
// eventually, call `resolve(..)` or `reject(..)`,
// which are the resolution callbacks for
// the promise.
} );
}
我会通过以下方式修复它:
function foo(x) {
// construct and return a promise
return new Promise( /* executor */ function(resolve,reject){
// start doing something that could take a while
// then foo returns the newly created Promise
// eventually, call `resolve(..)` or `reject(..)`,
// which are the resolution callbacks for
// the promise.
} );
}
最佳答案
是的,这个问题应该得到解决(感谢您提交 this issue )。
这让我想起了一点 difference between the deferred pattern and the revealing constructor pattern 。在 Promise 构造函数回调中启动异步任务有两个优点:
- 如果它同步抛出(例如语法错误、方法调用中的拼写错误等),异常将被隐式捕获并拒绝 promise
resolve
和reject
回调已在范围内,可以作为回调传递给异步进程。
关于javascript - Promise 中异步执行的代码在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570139/