![](/img/trans.png)
[英]How to wait for .map() to finish executing before continuing on to next lines of code
[英]Node - wait for map to finish before continuing
我在我的節點應用程序中有這個文件,它應該使用cheerio從他們的官方網站獲取有關每個聯賽冠軍的一些數據,並且一切順利但是當我將所有數據添加到我的數組然后將其作為json數據返回時寫入函數在地圖完成之前運行,所以我只是創建一個 json 文件,其中包含一個空數組:
const request = require('request');
const cheerio = require('cheerio');
const fs = require('fs');
const champions = fs.readFileSync('champions.json');
const championsObj = JSON.parse(champions);
let champsList = [];
championsObj.map(champ => {
request(champ.href, (err, res, html) => {
if (!err && res.statusCode == 200) {
const $ = cheerio.load(html);
const champName = $('.style__Title-sc-14gxj1e-3 span').text();
let skins = [];
const skinsList = $('.style__CarouselItemText-sc-1tlyqoa-16').each(
(i, el) => {
const skinName = $(el).text();
skins.push = skinName;
}
);
const champion = {
champName,
skins
};
console.log(champion);
champsList.push = champion;
}
});
});
const jsonContent = JSON.stringify(champsList);
fs.writeFile('champions2.json', jsonContent, 'utf8', function(err) {
if (err) {
console.log(err);
}
});
我不是節點專家,但我嘗試使用 Promise 但它沒有用,但我不確定我是否用錯了它。
更新 #1:使用 axios
championsObj.map(async champ => {
const html = await axios.get(champ.href);
const $ = await cheerio.load(html);
const champName = $('.style__Title-sc-14gxj1e-3 span').text();
let skins = [];
const skinsList = $('.style__CarouselItemText-sc-1tlyqoa-16').each(
(i, el) => {
const skinName = $(el).text();
skins.push = skinName;
}
);
const champion = {
champName,
skins
};
console.log(champion);
champsList.push = champion;
});
你可以使用await Promise.all(<array>.map(async () => {...})
。它不需要任何額外的依賴。但是你不能保證異步迭代的順序(開始所有迭代以正確的順序,但不能保證迭代的結束)。
您的問題是Array#map
在繼續之前不等待異步函數(例如request
調用)完成。 我推薦帶有got
p-map
。 為了保證完美的執行順序,我也推薦異步讀寫文件。
const got = require('got');
const pMap = require('p-map');
const cheerio = require('cheerio');
const fs = require('fs').promises;
(async () => {
const champions = JSON.parse(await fs.readFile('champions.json', 'utf8'));
let champsList = await pMap(champions, async champ => {
const {
body
} = await got(champ.href)
const $ = cheerio.load(body);
const champName = $('.style__Title-sc-14gxj1e-3 span').text();
let skins = [];
$('.style__CarouselItemText-sc-1tlyqoa-16').each(
(_, el) => {
const skinName = $(el).text();
skins.push(skinName);
}
);
const champion = {
champName,
skins
};
console.log(champion);
return champion;
})
await fs.writeFile('champions2.json', JSON.stringify(champsList));
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.