gpt4 book ai didi

javascript - NodeJS 循环内部包含异步函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:11 24 4
gpt4 key购买 nike

我遇到的问题是 for(var x=1; x < 6; x++)因为速度太快而被调用 axios.get()是异步的,但我不知道如何在解决方案过于复杂的情况下解决这个问题

const axios = require("axios");
const cheerio = require("cheerio");

function imdbGetData(id) {
var title, show, $;
var arr = [];
var airdates = [];
show = {
seasons: []
};

axios.get(`http://www.imdb.com/title/${id}/`).then((body) => {
$ = cheerio.load(body.data);
title = $("div h1").text()
});
for(var x=1; x < 6; x++) {
console.log(x); // Will count too 1,2,3,4,5,6
url = `http://www.imdb.com/title/${id}/episodes?season=${x}`
axios.get(url).then((body) => {
$ = cheerio.load(body.data);
console.log(x);// 6, 6, 6, 6
$("div .info .airdate").each(function(index, item) {
var airdate = String($(this).text());
airdates.push(airdate.trim());
});


$(".info strong a").each(function(i, item){
var airdate = airdates[i];

var epsiode_name = $(this).text()
if (epsiode_name && !epsiode_name.includes("#"))
arr.push({epsiode_name, airdate});
});
show.seasons.push(arr);
arr = []
// console.log(show.seasons);
});
setTimeout(() => {console.log(show.seasons)}, 10000) // ghetto
}
}

// season = {
// seasons: [[ {epsiode_name} ], [{Epsiode name}]]
// }

imdbGetData("tt2193021");

最佳答案

您可以构造所有 Promise 并将其推送到数组,然后使用 Promise.all(arrayOfPromises)。这样,您将保留异步链,并且可以轻松处理与常规单个异步操作非常相似的结果:

var promises = [];
for (var x = 1; x < 6; x++) {
url = `http://www.imdb.com/title/${id}/episodes?season=${x}`
promises.push(axios.get(url));
}

Promise.all(promises)
.then(body => {
// all results of promises will be in 'body' parameter
})
.catch(err => console.error(err));

关于javascript - NodeJS 循环内部包含异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48816681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com