简体   繁体   English

ES2017异步/等待功能 - 它们只适用于承诺吗?

[英]ES2017 Async/await functions - do they work only with promises?

I started using async/await ES7 functions in my js applications (transpiled by Babel). 我开始在我的js应用程序中使用async/await ES7函数(由Babel编译)。

Correct me if wrong, but do they work only with Promises? 纠正我,如果错了,但他们只与Promises合作吗? If yes, this means that I need to wrap regular callback functions into Promises (what I'm currently doing btw). 如果是,这意味着我需要将常规回调函数包装到Promises中(我目前正在做什么)。

The current (and likely final) async/await proposal awaits promises and desugars into something like bluebird's Promise.coroutine with await playing the part of yield . 当前(也可能是最终的)async / await提议等待承诺和desugars到像bluebird的Promise.coroutineawait播放yield的一部分。

This makes sense, as promises represent a value + time and you're waiting for that value to become available. 这是有道理的,因为promises代表一个值+时间,你正在等待该值可用。 Note await also waits for promise like constructs in all other languages that include it like C# or Python (3.5+) . 注意await还等待包括C#或Python(3.5+)在内的所有其他语言中的构造的承诺。

Note that converting callback APIs to promises is very easy, and some libraries offer tools to do so in a single command. 请注意,将回调API转换为promises非常简单,有些库提供了在单个命令中执行此操作的工具。 See How to convert an existing callback API to promises for more details. 有关更多详细信息,请参阅如何将现有回调API转换为承诺

Yes, you await a promise. 是的,你await一个承诺。

async function myFunction() {
  let result = await somethingThatReturnsAPromise();
  console.log(result); // cool, we have a result
}

http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM