faiizow
faiizow

Reputation: 85

How do I force synchronicity in node.js?

I've been trying to understand how I can force synchronicity in nodejs but I've failed at most attempts.

For example this code:

var r = require('request');
var a = require('async');

var hello = function (cb) {
  console.log('Hello from 1!');
  cb();
}

var random = function (cb) {
  console.log(Math.floor(Math.random() * 10));
  cb();
}

var google = function (cb) {
  r('http://google.com', function (err, res, body) {
    console.log(res.statusCode);
  });
  cb();
}

var bye = function (cb) {
  console.log('Bye from 3!');
  cb();
}

a.series([hello, google, random, bye], function () {
  console.log('done');
});

This does not work as you expect it to - in all my attempts the response code from Google always comes last.

Hello from 1!
7
Bye from 3!
done
200

How do I go about getting those functions to run one-by-one in order with or without the use of modules?

Upvotes: 1

Views: 634

Answers (1)

Mustafa
Mustafa

Reputation: 10413

Because in Google request code, you are calling callback without waiting for an answer. The correct way to do it should be:

var google = function (cb) {
  r('http://google.com', function (err, res, body) {
    console.log(res.statusCode);
    cb();
  });
}

Therefore, execution will go to next function if only the google response has arrived.

Upvotes: 2

Related Questions