使用fetch时如何在for循环中动态循环多个promise?

waz*_*waz 2 javascript for-loop node.js ecmascript-6 fetch-api

这是有效的:

    const limit = 1000
    // fetchMyProducts(page, limit, flag)
    return fetchMyProducts(1, 1, true)
    .then(function (products) {
        return fetchMyProducts(2, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(3, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(4, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(5, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(6, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(7, limit, false)
    })
Run Code Online (Sandbox Code Playgroud)

我正在尝试通过 fetch 获取我们系统中的所有产品。问题是,目前,我知道有多少产品,但在 1 年 / 3 年内......谁知道?

我正在尝试动态循环获取并获取所有产品。

我试过这个,但它似乎根本没有被调用。

    return fetchMyProducts(1, 1, true)
    .then(function (numberOfProducts) {
        let pages = Math.ceil(numberOfProducts / 1000) + 1;
        console.log(pages);
        return getAllProducts = () => {
            for (let i = 1; i < pages; i++) {
                const element = array[i];
                return fetchMyProducts(2, limit, false)

            }
        }
    }).then(... something else)
Run Code Online (Sandbox Code Playgroud)

有没有办法循环获取 fetch 承诺并在完成时返回一些东西,然后继续做其他事情?

Ber*_*rgi 7

你正在寻找

const limit = 1000
let chain = Promise.resolve();
for (let i=1; i<8; i++) {
    chain = chain.then(function(products) {
        return fetchMyProducts(i, limit, false)
    });
}
return chain;
Run Code Online (Sandbox Code Playgroud)

它动态地构建您拼写的承诺链。


要获得更简单有效的解决方案,请考虑使用async/ await

const limit = 1000
for (let i=1; i<8; i++) {
    const products = await fetchMyProducts(i, limit, false);
}
return;
Run Code Online (Sandbox Code Playgroud)