我正在嘗試從狗 API 中獲取資料,并且只想將它們的性情添加到我的資料庫中。我嘗試使用一些回圈和拆分來隔離資料,然后使用 findOrCreate() 僅添加那些尚未在資料庫中的人,之后我使用 findAll() 從資料庫中獲取該資訊以使用 expressJS 發送它。當我轉到執行所有這些的路線并且路線只給出大約一半的氣質(它們是 124 并且它顯示 54 左右)時,會出現意想不到的行為,然后當我重繪 頁面時,它會顯示所有 124 種氣質。資料庫一次性填充了所有 124 個,所以問題在于 findAll() 這是隔離氣質并將它們附加到資料庫的函式:
module.exports = async () => {
const info = await getAllDogs();
info.forEach(async (element) => {
const { temperament } = element;
if (temperament) {
const eachOne = temperament.split(", ");
for (i in eachOne) {
await Temperament.findOrCreate({
where: { name: eachOne[i] },
});
}
}
});
};
這是當我點擊我的 expressJS sv 以獲取資訊時執行的代碼
exports.temperaments = async (req, res) => {
try {
await getTemperaments(); //this function is the above function
} catch (error) {
res.status(500).send("something gone wrong", error);
}
const temperamentsDB = await Temperament.findAll();
res.json(temperamentsDB);
};
如您所見,最后一個函式執行將所有資料附加到資料庫的函式,然后使用 findAll 和 res.json() 發送它
uj5u.com熱心網友回復:
forEach是一種同步方法,因此它不會等待異步回呼的結果。您需要執行以下操作for of才能等待所有結果:
module.exports = async () => {
const info = await getAllDogs();
for (element of info) {
const { temperament } = element;
if (temperament) {
const eachOne = temperament.split(", ");
for (i in eachOne) {
await Temperament.findOrCreate({
where: { name: eachOne[i] },
});
}
}
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/439223.html
上一篇:嘗試為VueExpress應用程式發出Post請求時無法獲取/register節目
下一篇:NodeJs:承諾總是回傳未定義
