我正在尝试获取 X 数量的库存商品,一旦我拥有它们,我就不想再获取了。到目前为止,这是我的代码:
const numberOfInstockItemsToShow = 10;
let inStockCount = 0;
let cancellablePromise;
const promises = data.map((item) => {
return fetch(url, options).then((res) => {
if (res.ok) {
return res.json()
}
}).then((d) => {
inStockCount++;
if (inStockCount >= numberOfInstockItemsToShow) {
cancellablePromise.cancel();
}
return d;
});
});
cancellablePromise = Promise.all(promises).then((d) => {
console.log("all the files were created:", d);
});
我已在配置中将取消设置为 true,因此我认为这与我的狡猾代码有关。
感谢任何帮助:)
最佳答案
您可以使用Promise.some([...], count)
。第一个参数是一个数组,第二个参数是许多已解决的 promise ,视为已履行。 Reference
const numberOfInstockItemsToShow = 10;
const promises = data.map((item) => {
return fetch(url, options).then((res) => {
if (res.ok) {
return res.json()
}
});
});
Promise.some(promises, numberOfInstockItemsToShow).then((d) => {
console.log("all the files were created:", d);
});
请注意,达到计数
后,这不会取消任何进一步的 promise 。一旦解决了所需数量的 promise ,这就会简单地实现。
关于javascript - 获取 x 项时取消 Bluebirds Promise.all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45844999/