【问题标题】:async/await / assignments from function returns来自函数返回的异步/等待/分配
【发布时间】:2018-01-02 19:36:23
【问题描述】:

目前有一个简单的功能:

async function getItem(id) {
  const item = await ... doing a bunch of time consuming stuff
  return item;
}

来自同步语言,但仍然从表面上理解 async/await;我希望以下内容能够返回已解决的项目:

const item = getItem('items-8');
console.log(item); // Just getting a promise

这个问题有点“装饰性”,但由于 async/await 解决了回调,我希望能走得更远,甚至避免 thenables 的事情。

是否可以使用 async/await 获得这样的单行变量赋值?语法/代码结构是什么?

【问题讨论】:

  • stackoverflow.com/questions/14220321/… 的可能重复项。它涵盖了各种各样的东西,包括 Promise 和 async/await。
  • @estus 如果我们坚持主要答案的标题,我们有"ES2017+: Promises with async/await""ES2015+: Promises with then()"。让我对ES2017 部分以"then" 结尾的事实感到困惑;然后它应该被宣传为"ES2017+ with still a little bit of ES2015: Promises with async/await/THEN"。这或多或少是我问那里的原因,想知道是否可以使用单线模式

标签: asynchronous async-await es6-promise ecmascript-5


【解决方案1】:

async..await 是 ES6 Promise 的语法糖,它允许以类似同步的方式编写异步代码。使用 Promise 的代码不能同步,因为 Promise 是异步的。

为了以同步方式编写,使用getItem 的代码也应该驻留在async 函数中。如果它是顶级的并且不驻留在另一个函数中(如应用程序初始化代码),它可以驻留在asyncIIFE。

要么是

getItem('items-8').then(item => {
  ...
});

或者

// inside `async` function
const item = await getItem('items-8');
...

【讨论】:

  • 我开始明白了,它不可能在异步之外发生,对吧?我很困惑,例如async function returnValue(id) { let item = await getItem(id); return item }); let it = returnValue("items-8") 仍然会返回一个承诺
  • 是的,它确实会返回一个承诺。是的,我们需要在async 函数中调用async 函数,以保持代码同步,而不需要thens。
猜你喜欢
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2021-05-25
相关资源
最近更新 更多