简体   繁体   English

使用异步迭代来链接承诺

[英]Using an async iterable to chain promises

I have an array of items ( projects ) I want to upload, one by one in sequence.我有一系列要上传的项目( projects ),按顺序一个接一个。

I know how to do this by constructing a promise chain, but I wanted to try and use an async iterator and for...await .我知道如何通过构建承诺链来做到这一点,但我想尝试使用async迭代器和for...await

First I map the projects to arrow functions which will, when called, invoke the upload;首先,我将项目映射到箭头函数,该函数在调用时会调用上传; then I create an async iterable via an async generator function.然后我通过async生成器函数创建一个async可迭代对象。

Then I use for...await to loop over the async iterable.然后我使用for...await来循环async迭代。

Is this an idiomatic approach?这是惯用的方法吗?

For example, (p)=>()=>upload(p) looks strange to me, as does the IIFE (async function*() { for (let p of arr) yield p() }()) .例如, (p)=>()=>upload(p)对我来说看起来很奇怪,IIFE (async function*() { for (let p of arr) yield p() }())

 const upload = ({name}) => new Promise((resolve) => setTimeout(() => resolve(`Response for upload of: ${name}`), 1000)) const asyncIter = (arr) => (async function*() { for (let i of arr) yield i() }()) const uploadInSeries = async (arr) => { const iter = asyncIter(arr.map((i) => () => upload(i))) for await(let response of iter) { console.log(response) } } const projects = [{ name: "P1" }, { name: "P2" }, { name: "P3" }] uploadInSeries(projects)

This is not a usecase for an async iterable.这不是异步可迭代的用例。 Async iterables only make sense if you don't know wether you have a next element or not.只有当您不知道是否有下一个元素时,异步迭代才有意义。 In your case however, the number of requests is already known, so you can just do但是,在您的情况下,请求的数量已经知道,因此您可以这样做

 for(const el of arr)
   await request(el);

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

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