简体   繁体   English

如何使 API 在 for 循环中一一调用

[英]how to make API calls inside for-loop one by one

im currently working for a webapp using nodejs.我目前正在使用 nodejs 为 webapp 工作。 this is my first time using Node.这是我第一次使用 Node。 I have an items in array(topsongs_s[]) that will be pass (one by one) as an arguments to modules function tht get a data from a musixmatch API.我在数组(topsongs_s[])中有一个项目,它将作为 arguments (一个接一个)传递到模块 function 以从 musixmatch ZDB974238714CA8ADE634A7CE1D08 获取数据。

modules: https://github.com/c0b41/musixmatch#artistsearch example given in the modules:模块: 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);
})

and here is my code:-这是我的代码:-

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

i'm using a for loop to get the artist name from an array, and pass it into the modules function.我正在使用 for 循环从数组中获取艺术家姓名,并将其传递给模块 function。 but it seems that the function get the artist ID without a proper iteration.但似乎 function 在没有适当迭代的情况下获得了艺术家 ID。 i want it to be run one by one is there any other way to do this kind of operation?我希望它一个一个地运行有没有其他方法可以做这种操作?

Use async/await使用async/await

I have added comments in the code snippet for the explanation, it pretty straightforward.我在代码片段中添加了注释以进行解释,它非常简单。

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM