node.jsapimusixmatch

how to make API calls inside for-loop one by one


im currently working for a webapp using nodejs . this is my first time using 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 .

modules : https://github.com/c0b41/musixmatch#artistsearch example given in the modules :

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 . but it seems that the function get the artist ID without a proper iteration. i want it to be run one by one is there any other way to do this kind of operation ?


Solution

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