gpt4 book ai didi

javascript - 如何找出使用 Promise.any 解决的 promise ?

转载 作者:行者123 更新时间:2023-12-04 07:57:26 24 4
gpt4 key购买 nike

我正在用 Promise.all 做一些批量 IO ,但最终我一次创建了太多的 IO promise ,从而达到了打开文件的限制。因此,我创建了一个实用程序,最多可以运行 50 个批次的 promise 。
一种解决方案是将任务分成五十个批次,然后做Promise.all每批上。但更明智的解决方案是使用 Promise.any 在 promise 解决时循环使用 promise 。 .问题是,Promise.any只返回结果,而不返回返回的 promise 。
如何找出哪个已解决,以便我可以用新的 Unresolved 批次替换它?

最佳答案

没有本地方法可以找到 Promise那已经完成了。
但我想到了一个解决方法。基本上,我分配了每个Promise一个 id 然后我解构 Promise 的返回值并注销id和结果

const Promise4 = fetch('https://pokeapi.co/api/v2/ability/?limit=1&offset=20').then(response => response.json()).then(result => ({
id: 4,
result
}));
const Promise1 = fetch('https://pokeapi.co/api/v2/ability/?limit=1&offset=12').then(response => response.json()).then(result => ({
id: 1,
result
}));
const Promise2 = fetch('https://pokeapi.co/api/v2/ability/?limit=1&offset=5').then(response => response.json()).then(result => ({
id: 2,
result
}));
const Promise3 = fetch('https://pokeapi.co/api/v2/ability/?limit=1&offset=23').then(response => response.json()).then(result => ({
id: 3,
result
}));


Promise.any([Promise1, Promise2, Promise3, Promise4]).then(({
id,
result
}) => console.log(`Promise${id} returned`, result.results[0].name));

关于javascript - 如何找出使用 Promise.any 解决的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66628136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com