簡體   English   中英

如何使 API 在 for 循環中一一調用

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

我目前正在使用 nodejs 為 webapp 工作。 這是我第一次使用 Node。 我在數組(topsongs_s[])中有一個項目,它將作為 arguments (一個接一個)傳遞到模塊 function 以從 musixmatch ZDB974238714CA8ADE634A7CE1D08 獲取數據。

模塊: 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 循環從數組中獲取藝術家姓名,並將其傳遞給模塊 function。 但似乎 function 在沒有適當迭代的情況下獲得了藝術家 ID。 我希望它一個一個地運行有沒有其他方法可以做這種操作?

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM