Reputation: 145
I am beginning journey on JS and NodeJS. While writing a hello-world app encountered different behavior of setTimeout. It would be great if I could know the cause of this difference.
Scenario 1: response waits for 5 sec
Scenario 2: Request get resolved immediately though timeout is set for 5 second
Code difference in two scenario is; in Scenario-1 setTimeout has anonymous function and in scenario-2 it calls another function in the same module.
calculator.js
Scenario-1:
module.exports.addNumbers = function(numberArray){
return new Promise(function(fullfil, reject){
setTimeout(() => {
if(!(typeof numberArray === 'Array'))
reject('Not number elements found!');
},5000);
//fullfil(10000);
});
}
Scenario-2:
module.exports.addNumbers = function(numberArray){
return new Promise(function(fullfil, reject){
setTimeout(add(numberArray, fullfil, reject),5000);
//fullfil(10000);
});
}
function add(numberArray, fullfil, reject){
if(!(typeof numberArray === 'Array'))
reject('Not number elements found!');
}
Router (Same in both scenario):
var express = require('express');
var router = express.Router();
var calculator = require('../services/calculator');
router.get('/',function(req,res,next){
//res.writeHeader(200,{'content-type':'text/plain'});
res.send('Hello World - ' + JSON.stringify(res));
console.log(res);
});
router.get('/testpromise',function(req,res,next){
calculator.addNumbers('First Try')
.then(function(result){
res.send(' Final Result ## '+result);
})
.catch(function(err){
res.send(' ERROR MSG ## '+err);
console.error(' ERROR MSG ##' +err);
});
});
module.exports = router;
Upvotes: 2
Views: 757
Reputation: 328
function foo(varOne, varTwo) {
console.log(varOne, varTwo);
}
setTimeout(foo, 5000, 1, 2); // you pass the parameters after the time parameter
setTimeout(()=> {foo(1, 2)}, 5000); // you call the function inside an anonymous function
You can check this for more details : How can I pass a parameter to a setTimeout() callback?
Upvotes: 1
Reputation: 7509
The first argument to setTimeout
needs to be a function to call.
In your first example you are providing such a function (() => {}
):
setTimeout(() => {
if(!(typeof numberArray === 'Array'))
reject('Not number elements found!');
},5000);
In the second example however you are not passing in a function as the first argument, instead you are calling it straight away (hence it gets evaluated there and then).
setTimeout(add(numberArray, fullfil, reject),5000);
As far as I can see add(numberArray, fullfil, reject)
does not return a function.
You could do this to wrap it into a function:
setTimeout(() => add(numberArray, fullfil, reject),5000);
or make add
return a function:
function add(numberArray, fullfil, reject){
return () => {
if(!(typeof numberArray === 'Array'))
reject('Not number elements found!');
}
}
// or
function add(numberArray, fullfil, reject){
return function() {
if(!(typeof numberArray === 'Array'))
reject('Not number elements found!');
}
}
Upvotes: 1