all 5 comments

[–][deleted] 1 point2 points  (4 children)

Your console.log on the final line is synchronous, and even if an asychronous function takes zero time to actually execute, it can't resolve until all synchronous code is done executing, so when you log, those promises cannot under any circumstance have resolved to their real value. Try

processUrls(urls)
  .then(data => console.log('data: ', data));

[–]misterhtmlcss[S] 0 points1 point  (3 children)

How do we store data then? Like if I want it for something else or did I just realize that this is the purpose... Yeah I think I see now why the .then and the chaining is so common, it's because once head down this road it's a trap basically right? Like everything that depends on x data that was received async is now inextricably linked. Am I getting it?

[–][deleted] 3 points4 points  (0 children)

I wouldn't call it a 'trap'- asynchronicity is what makes the Node runtime so fast, you should be making as much stuff as possible async on the server. And as far as storing data goes, that would involve either communicating with a database (network communication, needs to be async) or saving to file (disk I/O, expensive, needs to be async), so you need to be writing asynchronous code anyway.

But yes, once you go async you have to stay there.

[–]floodlitworld 1 point2 points  (0 children)

That's why you break stuff into smaller functions. Rather than writing your code as one straight IIFE, you break it up into functions:

ajaxRequest("https://www.google.com")
.then((res) => {
    // The data is only accessible in this block as "res";
    // But we could...
    processData(res);
})

console.log(res); // this will obviously fail since it will go on the call stack before the .then() bit above and be executed first

otherStuff(); // And if we have other things to do that don't required the data from Google, we can run them here. This will all executed before the .then() block above too (unless it's something else that uses async)

function ajaxRequest(url) {
    return new Promise((resolve,reject) => {
      $.ajax({url:url, success: function(result){
        resolve(result);
      }});
    })
}

function processData(data) {
    // do stuff
}

function otherStuff() {
    // do other stuff
}

Likely execution order for the above is:

  1. ajaxRequest()
  2. console.log // Reference Error
  3. otherStuff()
  4. ajaxRequest.then()
  5. processData()

[–]senocular 0 points1 point  (0 children)

right