0

我目前正在使用 nodejs 为 webapp 工作。这是我第一次使用 Node。我在 array(topsongs_s[]) 中有一个项目,它将(一个接一个)作为参数传递给模块函数,以从 musixmatch API 获取数据。

模块: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 循环从数组中获取艺术家姓名,并将其传递给模块函数。但似乎该函数在没有适当迭代的情况下获取艺术家 ID。我希望它一个一个地运行有没有其他方法可以做这种操作?

4

1 回答 1

2

采用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);
        }
    }

}
于 2021-02-09T09:27:44.213 回答