【问题标题】:how to make API calls inside for-loop one by one如何在for循环中一一进行API调用
【发布时间】:2021-05-12 21:47:39
【问题描述】:

我目前正在使用 nodejs 为 webapp 工作。这是我第一次使用 Node。 我在数组(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。我希望它一个一个运行 有没有其他方法可以做这种操作?

【问题讨论】:

    标签: node.js api musixmatch


    【解决方案1】:

    使用async/await

    我在代码 sn-p 中添加了 cmets 进行解释,非常简单。

    // 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);
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-26
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多