javascript - 获取 x 项时取消 Bluebirds Promise.all

标签 javascript promise fetch bluebird cancellation

我正在尝试获取 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/

相关文章:

javascript - 未分配的 Promise 及其关联的处理程序存储在哪里

reactjs - 仅当状态为 true 时才应用获取回调

javascript - 使用 fetch api 下载文件

Javascript:可以访问返回json的url,但是在获取时发生错误

javascript - Parse.Promise 上的成功/错误

node.js - 在 node.js 中永远重复这组 Action

javascript - 为什么我的 Canvas 在一段时间后性能会下降?

javascript - 将日期时间数据从 Django 传递到 Javascript

javascript - 将客户端的数据传递到服务器 Node

javascript - 如何访问以下数组中的 ID 和 pID?