Mad*_*ist 7 javascript async-await typescript
我一直在尝试使用Typescript,但我现在对如何有效地使用async/await感到困惑.
我正在将一堆记录插入到数据库中,我需要获取每个插入返回的ID列表.以下简化示例通常起作用,但它并不像我想的那么优雅,而且完全是顺序的.
async function generatePersons() {
const names = generateNames(firstNames, lastNames);
let ids = []
for (let name of names) {
const id = await db("persons").insert({
first_name: name.firstName,
last_name: name.lastName,
}).returning('id');
ids.push(id[0])
}
return ids
}
Run Code Online (Sandbox Code Playgroud)
我试图用来map避免ids手动创建列表,但我可以让它工作.
我还想拥有的是有限的并行性.所以我的异步调用应该并行发生,直到某个限制,例如,我只想要有10个开放请求,但不是更多.
在Typescript或Javascript ES7中使用async/await实现这种有限的并行性是否有一种相当优雅的方式?或者我是否试图让这个功能做一些不适合的事情?
PS:我知道有数据库的批量插入方法,这个例子有点人为,因为我可以使用它来解决这个特定的问题.但它让我想知道我没有预定义批量方法的一般情况,例如网络请求
Promise.all 将允许您等待所有请求停止完成,而不会阻止他们的创建.
但是,它确实听起来像你想有时阻止.具体而言,这听起来像你想扼杀在飞行的请求数在任何给定的时间.这是我掀起的东西(但尚未经过全面测试!)
async function asyncThrottledMap<T, U>(maxCount: number, array: T[], f: (x: T) => Promise<U>) {
let inFlight = new Set<Promise<U>>();
const result: Promise<U>[] = [];
// Sequentially add a Promise for each operation.
for (let elem of array) {
// Wait for any one of the promises to complete if there are too many running.
if (inFlight.size >= maxCount) {
await Promise.race(inFlight);
}
// This is the Promise that the user originally passed us back.
const origPromise = f(elem);
// This is a Promise that adds/removes from the set of in-flight promises.
const handledPromise = wrap(origPromise);
result.push(handledPromise);
}
return Promise.all(result);
async function wrap(p: Promise<U>) {
inFlight.add(p);
const result = await p;
inFlight.delete(p);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
以上inFlight是目前正在进行的一系列操作.
这result是一个包裹 Promise的数组.每个包装的promise都基本上添加或删除操作集中的inFlight操作.如果飞行中的操作太多,则可以使用Promise.race任何一个飞行中的操作来完成.
希望这会有所帮助.
bas*_*rat -1
在 Typescript 或 Javascript ES7 中是否有一种相当优雅的方法来实现这种使用 async/await 的有限并行性
你将不得不使用Promise.all. 即收集数组中的所有承诺并await Promise.all([all,the,stuff])。
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
| 归档时间: |
|
| 查看次数: |
1617 次 |
| 最近记录: |