The purpose of async/await functions is to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises. Just as Promises are similar to structured callbacks, async/await is similar to combining generators and promises.
我了解异步/等待、生成器和 promise 的基本概念。但是,我不完全理解说 async/await 类似于组合生成器和 promises 是什么意思。
那么 async/await 简化了生成器和 promises 可以一起做什么?有什么例子吗?
最佳答案
是的,你是对的。首先使用生成器和 promises 的示例:
function *gen () {
const promiseValue = yield new Promise((resolve) => resolve(42));
console.log(promiseValue);
}
// .. and at some other context using '*gen'
const iterator = gen();
const { value: promise } = iterator.next(); // Promise (42)
promise.then((resolvedValue) => iterator.next(resolvedValue)); // logs 42
这个生成器向外界产生一个 Promise
,我们通过将其作为参数传递给 iterator.next
调用将其值传递回生成器,一次这个 promise 解决了。
此模式至少与所谓的任务 相交。这样做的缺点是,每次 yielded promise 解析时,我们都必须在迭代器上手动调用 next
。这就是 async await
的用武之地:
async function task() {
const promiseValue = await new Promise((resolve) => resolve(42));
console.log(promiseValue);
}
这就是它的全部。异步函数将暂停,直到以 await
关键字开头的 promise 表达式解析,并且该表达式将计算为自动 unwrap promise - 即它的最终值。
然后等待表达式的结果(42
,在我们的例子中)将被分配给 promiseValue
,就像 yield
一样。这一切都发生在函数继续执行到下一条语句之前。
这与上面带有生成器的代码片段本质上是相同的行为。
尽管根据我的经验,这个示例似乎是生成器和异步函数最常见的用例,其中 async/await 绝对是更简洁的方法,生成器确实有一些非常强大的功能,而 async/await 没有以同样的方式(但这是另一个话题)。
关于javascript - 异步/等待 vs 组合生成器和 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46043201/