1

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.

1
  • 1
    See npmjs.com/package/sleep. It says These calls will block execution of all JavaScript by halting Node.js' event loop! Commented Feb 24, 2016 at 21:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

OK that makes sense. I was using sleep to simulate something that took a few seconds to do. How can I make a function asynchronous without having the setTimoutout? Or are functions naturally asynchronous unless they call a blocking method?
Javascript is synchronous. But most libraries written in C, like IO and other functions are asynchronous. What kind of functions do you want to make async?
I want to do several REST calls then collect all the results and process the data. Is there a way to tell if a function is blocking or non-blocking? And is there a way to make your own non-blocking asynchronous function?
To make it yourself you have to write it in C, or use functions that are async. async functions in JS are either using the callback or the Promise pattern, so they are easy to spot. request library for instance is async, so that should be easily achievable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.