亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試傳遞數組并使用foreach發回多個數據

嘗試傳遞數組并使用foreach發回多個數據

蝴蝶刀刀 2023-07-20 15:41:37
我有 getProductInfo orgianlly,作為兩個參數,它的位置是(res,sku)。但現在我想傳遞一個帶有 sku 編號的集合對象和 for-each 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: 錯誤: 超出最大重試次數”
查看完整描述

1 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

ASYNC / AWAIT您可以使用和的組合Promise.all來按預期填充allProductInfo

需要注意的ASYNC / AWAIT是,您只能在 ASYNC 函數內使用 ASYNC 函數。

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);

};


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號