我目前正在为一个使用nodejs的webapp应用程序工作。这是我第一次使用Node。我在数组(topsongs_s[])中有一个项目,它将作为参数传递(一个接一个)给模块函数,以便从musixmatch获取数据。
模块:模块中给出的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循环从数组中获取艺术家姓名,并将其传递给modules函数。但似乎该函数在没有适当迭代的情况下获得了艺术家ID。我想要一个接一个地运行,有没有其他方法来做这种操作?
发布于 2021-02-09 17:27:44
使用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);
}
}
}https://stackoverflow.com/questions/66116010
复制相似问题