我开始了JS和NodeJS之旅。在编写hello-world应用程序时,遇到了setTimeout的不同行为。如果我能知道这种差异的原因,那就太好了。
场景1:响应等待5秒
场景2:请求立即得到解析,但超时设置为5秒
两个场景中的代码差异是;在场景1中,setTimeout具有匿名函数,而在场景2中,它调用同一模块中的另一个函数。
calculator.js
场景-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);
});
}
场景-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!');
}
路由器(两种方案相同):
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;
发布于 2018-06-01 03:40:05
setTimeout
的第一个参数需要是要调用的函数。
在您的第一个示例中,您提供了这样一个函数(() => {}
):
setTimeout(() => {
if(!(typeof numberArray === 'Array'))
reject('Not number elements found!');
},5000);
然而,在第二个例子中,你并没有把一个函数作为第一个参数来传递,而是直接调用它(因此它会立即被计算)。
setTimeout(add(numberArray, fullfil, reject),5000);
据我所知,add(numberArray, fullfil, reject)
不会返回函数。
您可以这样做,将其封装到一个函数中:
setTimeout(() => add(numberArray, fullfil, reject),5000);
或者让add
返回一个函数:
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!');
}
}
发布于 2018-06-01 03:59:51
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
有关更多详细信息,请查看以下内容:How can I pass a parameter to a setTimeout() callback?
https://stackoverflow.com/questions/50631556
复制相似问题