Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs run task in sequence

I am new to node.js and I just don't know how to execute a settimeout function before another function,

for example,

var async = require('async');
function hello(){
    setTimeout(function(){
        console.log('hello');
    },2000);}

function world(){
    console.log("world");
}
async.series([hello,world()]);

and the output is always world hello.

Am I using the library right? I dont the question seems trivial but I really have no idea how to force a short task to run after a long one

like image 223
Paros Kwan Avatar asked Mar 10 '23 12:03

Paros Kwan


2 Answers

Async requires you to use callback. Follow this link to see some examples. The following code should output hello world correctly:

var async = require("async");
function hello(callback) {
    setTimeout(function(){
        console.log('hello');
        callback();
    }, 2000);
}

function world(callback) {
    console.log("world");
    callback();
}

async.series([hello, world], function (err, results) {
    // results is an array of the value returned from each function
    // Handling errors here
    if (err)    {
        console.log(err);
    }
});

Note that callback() was called inside the setTimeout() function so that it waits for the console.log('hello').

like image 89
Divyanshu Maithani Avatar answered Mar 16 '23 16:03

Divyanshu Maithani


Use promise

function hello(){
    return new Promise(function(resolve, reject) {
        console.log('hello');
        resolve();
    });
}

function world(){
   return new Promise(function(resolve, reject) {
      console.log("world");
      resolve();
    });
}


  hello()
  .then(function(){
     return world()
  })
  .then(function(){
    console.log('both done');
  })
  .catch(function(err){
     console.log(err);
  });
like image 44
Gaurav joshi Avatar answered Mar 16 '23 15:03

Gaurav joshi