【问题标题】:Trying to pass array and use foreach to send back multiple data尝试传递数组并使用 foreach 发回多个数据
【发布时间】:2021-02-21 17:30:01
【问题描述】:

我有 getProductInfo orgianlly,作为两个参数,它会在哪里(res,sku)。但现在我想传递一个带有 sku 编号的集合对象并为每个 res.send 发送数据


const activeProductBank = new Set([6401728, 6430161, 6359222, 6368084]);

getProductInfo = (res) => {
    activeProductBank.forEach((SKU) => {
        bby.products(SKU, { show:'sku,name' })
        .then(function(data) {
            res.send(data);
        });
    })
};

也试过了

getProductInfo = (res) => {
    const allProductInfo = '';

    activeProductBank.forEach((SKU) => {
        bby.products(SKU, { show:'sku,name'})
        .then(function(data) {
            allProductInfo.concat(data);
        });
    })
    res.send(allProductInfo);
};

我得到“应用程序在 http://localhost:3000 监听”的错误 (node:25556) UnhandledPromiseRejectionWarning: E​​rror: Exceeded max retries"

【问题讨论】:

    标签: javascript api express routes


    【解决方案1】:

    您可以使用ASYNC / AWAITPromise.all 的组合来按预期填充allProductInfo

    ASYNC / AWAIT 的警告是您只能在 ASYNC 函数中使用 ASYNC 函数。更多信息在这里https://javascript.info/async-await

    activeProductBank.map 将遍历您的所有 activeProductBank 并返回一个 Promise 数组,然后将其传递给 Promise.all,然后在解决列表中的所有 Promise 后解析。

    Promise.all

    getProductInfo = async (res) => {
    
        const allProductInfo = Promise.all(
                                    activeProductBank.map(SKU => bby.products(SKU, { show:'sku,name'}))
                                )
        
        res.send(allProductInfo);
    };
    

    另一种方法是使用 for..of 循环并使用如下所示的 Await 调用逐个推送每个 productInfo 的响应

    getProductInfo = async (res) => {
        let allProductInfo = [];
    
        for(let sku of allProductInfo) {
            const productInfo = await bby.products(sku, { show:'sku,name'});
            allProductInfo.push(productInfo);
        }
        
        res.send(allProductInfo);
    };
    

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 2016-01-20
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多