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
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').
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);
  });
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With