[英]how to make API calls inside for-loop one by one
我目前正在使用 nodejs 为 webapp 工作。 这是我第一次使用 Node。 我在数组(topsongs_s[])中有一个项目,它将作为 arguments (一个接一个)传递到模块 function 以从 musixmatch ZDB974238714CA8ADE634A7CE1D08 获取数据。
模块: https://github.com/c0b41/musixmatch#artistsearch模块中给出的示例:
music.artistSearch({q_artist:"prodigy", page_size:5})
.then(function(data){
console.log(data);
}).catch(function(err){
console.log(err);
})
这是我的代码:-
for (let index = 0; index < topsongs_s.length; index++) {
var artistName = topsongs_s[index].artists[0].name; //get the artist name in the array
console.log(artistName); //print the artist name
music.artistSearch({
q_artist: artistName, //pass the artist name
page_size: 1
})
.then(function (data) {
console.log(data.message.body.artist_list[0].artist.artist_id); //print the artist_id from musixmatch api
console.log();
}).catch(function (err) {
console.log(err);
})
}
我正在使用 for 循环从数组中获取艺术家姓名,并将其传递给模块 function。 但似乎 function 在没有适当迭代的情况下获得了艺术家 ID。 我希望它一个一个地运行有没有其他方法可以做这种操作?
使用async/await
我在代码片段中添加了注释以进行解释,它非常简单。
// you need to add "async" keyword to your function
// to use async/await functionality
async function callAPI() {
for (let index = 0; index < topsongs_s.length; index++) {
// use try/catch for error handling
try {
var artistName = topsongs_s[index].artists[0].name; //get the artist name in the array
console.log(artistName); //print the artist name
// call synchronously and wait for the response
const data = await music.artistSearch({
q_artist: artistName, //pass the artist name
page_size: 1
});
console.log(data.message.body.artist_list[0].artist.artist_id); //print the artist_id from musixmatch api
console.log();
} catch (error) {
console.error(error);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.