简体   繁体   中英

Code executing in wrong order and it isn't async (I think…)

I have this code below. Why does console.log("done:) execute before the loop finishes? I get it that "request" is async but my console.log is inside the callback function. The callback function is synchronous (as far as I can see) and starts going through the loop, then when the loop finishes it should execute my console.log("done"). But it doesn't. It executes it before (or right after the first iteration of the loop). Is the loop async too? It's the only way I could explain what is happening.

const request = require('request');

var item_urls;
var options = {
    json: true
  };
var test = [] ;


function updateDB (){
    var url = "https://api.warframe.market/v1/items";


    request(url, options, (error, res, body) =>{
        if (error) {
            return console.log(error)
          };

          if (!error && res.statusCode == 200) {
            console.log("executing cb1");
            item_urls = body.payload.items;
            var primes = item_urls.filter(item => item.item_name.includes("Strun Wraith Set"));
            for (item in primes) // Loop through items, then and add to recipelist. This is to make it the same name as the URL attribute.
            {
                let url = `https://api.warframe.market/v1/items/${primes[item].url_name}`;
               // console.log (url);
                request(url, options, (error, res, body) =>{
                    if (error) {
                        return console.log(error)
                      };

                      if (!error && res.statusCode == 200) {

                          console.log(`Getting item ${url}`);
                          test.push(body.payload.item);
                      }
                    });

            };  
            console.log ("done");          


          };
    });
}
updateDB ();

The for loop is NOT asynchronous and the console.log("done") does indeed run after the loop. However you are making an asynchronous request within the for loop which is why you're seeing the inner request callback's console.log afterwards.

request(url, options, (error, res, body) => { ... })

Even without knowing anything about request , you can tell this is an asynchronous function invocation: instead of returning a result, it accepts a function to run on said result.

Synchronous invocation would have looked like this:

let [error, res, body] = request(url, options);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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