【问题标题】:Is async/await not intended for global synchronous use?async/await 不适合全局同步使用吗?
【发布时间】:2018-06-21 16:03:41
【问题描述】:

我希望这段代码:

function resolveAfter2Seconds() {
  return new Promise(resolve => 
    setTimeout(() => { resolve('resolved'); }, 2000) );
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
}

asyncCall();
asyncCall();

要产生这个输出:

"calling"
"resolved"
"calling"
"resolved"

但是我得到了这个:

 "calling"
 "calling"
 "resolved"
 "resolved"

我必须这样做才能使我的代码同步:

function resolveAfter2Seconds() {
  return new Promise(resolve => 
    setTimeout(() => { resolve('resolved'); }, 2000) );
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
}

const main = async () => {
  await asyncCall();
  await asyncCall();
};

main();

这意味着如果我在函数调用树的深处有一个 await 调用,我必须在我的函数链中一直使用 async/await 才能获得整个应用程序的同步行为?这对我来说似乎很繁重。请告诉我我错了。这绝对消除了我对 async/await 的大部分好感:(

【问题讨论】:

  • async/await 不会改变您在单个非阻塞线程中工作的事实。所以,是的,您需要使用第二种方法或类似的方法来获得您期望的结果。
  • async/await 不会使任何东西同步。它是异步逻辑的语法,与同步代码无关。
  • 如果第一个代码 sn-p 做了你想让它做的事情,那将是非常有问题的。不可能同时启动两个或多个异步请求。
  • 这将需要解释器更改以使异步函数阻塞并且不返回异步本身。但这应该是可行的。 (下面的每个 Crowder 都有一个第 2 阶段的提案,所以这是可能的)。
  • 有一个提议允许在模块范围内使用await。没有建议使异步功能阻塞。 async 函数返回 Promise 对象;这就是他们的重点。

标签: javascript asynchronous


【解决方案1】:

前两个asyncCalls 重叠的原因是您没有await 他们。所以第一个开始超时,返回,然后你调用第二个,它也开始超时并返回。

async/await 是否不适合全局同步使用?

是和不是。您只能在async 函数中使用await(尽管有一个Stage 2 proposal 来添加顶级await),所以(无论如何,现在)您不能在全局范围内使用await。但是您没有理由不能立即切换到 async 函数,例如您的 main 甚至只是内联:

(async () => {
    // Use await here...
})().catch(err => {
    // Last-ditch error handling here
});

或

(async () => {
    try {
        // Use await here...
    } catch (err) {
        // Last-ditch error handling here
    }
})();

【讨论】:

  • 顶级await 有一个stage-2 proposal...虽然这也不是没有问题。
  • @JaredSmith - 谢谢 - 一个路过我。
  • @JaredSmith - 我错过了它,还是仅针对顶级await in modules 的提案? (并不是说模块不应该开始成为我们默认的顶级......)
  • 是的,并且提案的一种变体只在没有导出的模块中(大概是为了避免依赖图中长时间阻塞负载的情况)。
  • @JaredSmith - 再次感谢!
猜你喜欢
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 2017-06-30
  • 2017-09-17
  • 2019-10-24
  • 2018-07-10
相关资源
最近更新 更多