javascript - Promise 中异步执行的代码在哪里?

标签 javascript asynchronous promise es6-promise

以下 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
  • resolvereject 回调已在范围内,可以作为回调传递给异步进程。

关于javascript - Promise 中异步执行的代码在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570139/

相关文章:

javascript - 为什么加载事件的 addEventListener 不适用于 div?

JavaScript 没有兑现 promise

angular - Typescript 中的对象类型不存在属性

javascript - MDN 上的代码 : how does this IE specific shim for setTimer work?

javascript - 在模式中滚动

.net - 我可以使用委托(delegate)的单个实例来启动多个异步请求吗?

c++ - C#/C++ 异步反向 pinvoke?

ios - 异步数据调用 & CoreAnimation

node.js - 无法 promise 具有带有 'Async' -后缀的正常方法的 API

javascript - Chrome 扩展程序可以关闭当前选项卡吗?