首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在for循环中逐个进行API调用

如何在for循环中逐个进行API调用
EN

Stack Overflow用户
提问于 2021-02-09 17:16:36
回答 1查看 46关注 0票数 0

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

模块:模块中给出的https://github.com/c0b41/musixmatch#artistsearch示例:

代码语言:javascript
复制
music.artistSearch({q_artist:"prodigy", page_size:5})
    .then(function(data){
        console.log(data);
    }).catch(function(err){
        console.log(err);
})

下面是我的代码:

代码语言:javascript
复制
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。我想要一个接一个地运行,有没有其他方法来做这种操作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-09 17:27:44

使用async/await

我在代码片段中添加了注释用于解释,它非常简单。

代码语言:javascript
复制
// 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);
        }
    }

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66116010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档