我正在嘗試將資料庫結果的輸出推送到一個名為“陣列”的變數中。但是在流程結束時,我的控制臺中出現了一個空值。但是在“then”函式內部,資料即將到來。data.foreach 的大小約為 30。我使用的是 Nodejs 14 和 sequelize 4。
let array=[];
data.forEach(async element => {
await SelectedTech.findAll({ where: { Requirement_id: element } }).then(async data => {
array.push(data);
}).then(async data => {
array.push(data);
});
await SelectedDomains.findAll({ where: { Requirement_id: element } }).then(async data => {
array.push(data);
}).then(async data => {
array.push(data);
});
await SelectedRoles.findAll({ where: { Requirement_id: element } }).then(async data => {
array.push(data);
}).then(async data => {
array.push(data);
});
await SelectedQualifications.findAll({ where: { Requirement_id: element } }).then(async data => {
array.push(data);
}).then(async data => {
array.push(data);
});
});
console.log(array);
uj5u.com熱心網友回復:
似乎你await在 forEach 回圈中有多個。您的回圈不會按預期作業,因為 forEach 會觸發多個異步呼叫。當您必須在回圈中處理異步操作時,這不是正確的方法。
你應該使用for..of它來幫助你實作它。
const array=[];
for (const da of data) {
const data = await SelectedTech.findAll({ where: { Requirement_id: element } });
array.push(data);
const data1 = await SelectedDomains.findAll({ where: { Requirement_id: element } });
array.push(data1);
const data2 = await SelectedRoles.findAll({ where: { Requirement_id: element } })
array.push(data2);
const data3 = await SelectedQualifications.findAll({ where: { Requirement_id: element }})
array.push(data3);
}
console.log(array);
注意:如果您使用,async/await請不要將其與 then/catch 混合使用,反之亦然。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404739.html
標籤:
上一篇:Express網關回傳無法GET
