Why doesn’t it work like this? The returned a is undefined. Logically speaking, the code is executed sequentially. Res.send will not be executed until s has a value.
Should res.send(s)
or res.send(s())
?
If a function is assigned to a variable, will the variable be executed when it is declared?
Is s executed when the following code declares s?
app.use("/test2",function(req,res,next){
var s=utils.Test(function(value){
console.log("value",value)
console.log("!!!")
return value
})
res.json(s())
})
The following way of writing can be used
app.use("/test2",function(req,res,next){
utils.Test(function(value){
console.log("value",value)
console.log("!!!")
res.json(s)
})
})
utils.Test()
utils.Test=function(callback){
request("http://localhost:3000/test/1.json",(err,res,body)=>{
let result=JSON.parse(body)
console.log("result",result)
// console.log(typeof result)
callback(result)
})
}
我想大声告诉你2017-05-19 10:09:46
Is there something wrong with the code you gave? But it’s probably because the result hasn’t been returned yet. If you put it in the callback function and execute it, there won’t be this problem. utils.Test
是一个异步执行的函数吧,所以你第一种写法在执行res.json(s)
PHP中文网2017-05-19 10:09:46
app.use("/test2",function(req,res,next){
var s=utils.Test(function(value){
console.log("value",value)
console.log("!!!")
return value
})
res.json(s())
})
Where does this code declare that s is a function? What gives you the confidence to insist that s must be a function and call s with all your heart?
If you assign a function to a variable, will the variable be executed when it is declared?
You did not assign a function to a variable. You passed the function to a function called utils.Test as the first parameter, and then gave the return value to the variable.
What do you mean by s? Then you have to ask utils.Test, dear, who knows what utils.Test does, who knows what the function you passed in has experienced in utils.Test.