我正在NodeJS中開發一個API,該API將在foreach回圈結束后發送一個回應,其中包括回圈內完成的每個操作的結果。 現在的問題是,代碼不能等到 foreach 完成后再發送回應。
Request:
"enterpriseName"/span>。"myEnterprise",
"渠道": [
{
"提供商": "mail",
"聯系人": "11111111111",
"配置": [
{
"name"/span> : "token"/span>,
"value" :"1234567890"。
}
]
},
{
" provider": "電話",
"聯系人": "123456789",
"配置": [
{
"name"/span> : "access_token"/span>,
"value" :"987654321".
}
]
}
]
}
代碼:
app. post('/channelEnterprise', (req, res) => /span> {
var output = [];
checkEnterpriseByName(req.body.enterpriseName, knex) 。 then((exist) =>/span> {
if (exist) {
req.body.channels.forEach(span class="hljs-params">channel => {
addChannel(req.body.enterpriseName, channel, knex) 。 then((channelEnterpriseId) =>/span> {
output.push({'provider'/span> : channel.provider,
'Id': channelEnterpriseId[0] 。
'result': 'ok'。
})
res.json(output)
});
});
}else{
res.status(500).send({error: '企業' req.body.enterpriseName ' 不存在。嘗試創建之前的企業,然后添加通道' })。
}
})
})
目標: 我們的目標是在foreach完成后才運行res.json(output),具體方法是:
[
{
"provider"。"mail",
"Id": 15,
"result": "ok"。
},
{
"提供者": "phone",
"Id": 16,
"result": "ok".
}
]
uj5u.com熱心網友回復:
不要使用foreach,你應該使用map函式,并使用Promise.all來等待map。同時,使用async/await來獲得更好的體驗。
試試這個
app.post('/channelEnterprise',async(req, res)=> {
const exist = await checkEnterpriseByName(req.body.enterpriseName, knex) 。
if(存在) {
let output = [];
await Promise.all(
req.body.channels.map(async channel => {
const channelEnterpriseId = await addChannel(
req.body.enterpriseName,
渠道。
渠道
);
output.push({
provider: channel.provider,
Id: channelEnterpriseId[0] 。
result: 'ok'。
});
})
);
res.json(output)。
} else {
res.status(500).send({
error:
'企業'
req.body.enterpriseName
' 不存在。嘗試創建之前的企業,然后添加通道'。
});
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/318047.html
標籤:
上一篇:gRPC服務器關閉時永遠掛起
