javascript - js function execution order problem, if the function is assigned to a variable, is it executed?
给我你的怀抱
给我你的怀抱 2017-05-19 10:07:46
0
2
516

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.

Shouldres.send(s)orres.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) }) }
给我你的怀抱
给我你的怀抱

reply all (2)
我想大声告诉你

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)

    Ty80
    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.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!