Alex
Alex

Reputation: 1999

How To Use NodeJS Module await?

I have the following code that uses the await module which technically work (I think).

var await = require('await')
var sleep = require('sleep')

var things = await('one', 'two');

function getData(key){      
  console.log("IN FUNCTION " + key);
  sleep.sleep(5);
  var data = "got data for " + key;
  things.keep(key, data);
  console.log("DONE WIH FUNCTION " + key);
}


console.log("start");
getData('one');
getData('two');
console.log('end');

things.then(function(got){
  console.log(got.one);
  console.log(got.two); 
} 
);

The output is:

start
IN FUNCTION one
DONE WIH FUNCTION one
IN FUNCTION two
DONE WIH FUNCTION two
end
got data for one
got data for two

Everything seems to get passed along as it should fulfilling promises. However, It looks like it is executing synchronously not asynchronously. I would have expected to see:

start
IN FUNCTION one
IN FUNCTION two
DONE WIH FUNCTION one
DONE WIH FUNCTION two
end
got data for one
got data for two

It also takes about 10 seconds which it should only take barley over 5 seconds.

Upvotes: 1

Views: 438

Answers (1)

bolav
bolav

Reputation: 6998

sleep is blocking, and not returning control to the event loop, so your code just sleeps right where it says sleep.

If you convert it to async, with setTimeout like this:

function getData(key){      
  console.log("IN FUNCTION " + key);
  setTimeout(function() {
    var data = "got data for " + key;
    things.keep(key, data);
    console.log("DONE WIH FUNCTION " + key);
  }, 5000);
}

I get this output:

start
IN FUNCTION one
IN FUNCTION two
end
DONE WIH FUNCTION one
got data for one
got data for two
DONE WIH FUNCTION two

Which looks correct to me.

Upvotes: 1

Related Questions