Chouffe
Chouffe

Reputation: 13

Promise async call

I am new to node js and trying to understand how to make async calls. I am trying to wrap a function into a promise in order to make it async. For simplicity, the function is just a loop that takes time :

var p = new Promise(resolve => {
    for (let i=0;i<999999999;i++){}
    resolve('foo')
});

p.then(function (value) { console.log(value);});
console.log('bar');

I am expecting to see :

bar // printed immediately

foo // printed after the loop finishes

Instead, they are both printed after the loop completion. How to make the loop block run asynchronously?

Ps. Apologies for the indentation/formatting, I had to write this from a phone.

Thanks

Upvotes: 0

Views: 53

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138234

You seem to assume that "asynchronous code" involves concurrency, in the sense that code will run at the same time in another thread. That is not the case. Unless you start another thread by purpose, JS itself will run in a single thread. Therefore no matter what you do with promises: Either the loop runs first and then the logs run or the logs run first and then the loop runs.

You could also achieve concurrent execution through multitasking: If you stop the loop inbetween, other code can run in the meantime:

 (async function() {
    while(true) {
       console.log("loop");
       await Promise.resolve();
    }
 })();

 console.log("in the meantime");

Upvotes: 2

mbojko
mbojko

Reputation: 14669

But there's nothing asynchronous about your promise. Creating a promise starts the execution of the function, and JS always runs to completion.

Typically, a promise is used to initiate something asynchronous, like an API call, or even a plain setTimeout, that runs outside JS's thread. Your code, however, will iterate through the empty loop bajillion times, and only after that any following lines will be run.

Replace the empty line with a timeout, and it will become async:

var p = new Promise(resolve => {
  setTimeout(() => resolve("foo"), 2000);
});

p.then(function(value) {
  console.log(value);
});
console.log('bar');

Upvotes: 2

Related Questions