Why is it possible to pass in a non-function parameter to Promise.then() without causing an error?

后端 未结 3 1195
天命终不由人
天命终不由人 2020-12-10 19:34

I have the following:

new Promise(resolve => setTimeout(resolve, 2000))
    .then(() => console.log(\"after 2 seconds\"));

new Promise(resolve => s         


        
3条回答
  •  渐次进展
    2020-12-10 20:00

    The code

    console.log("before 3 seconds (instantly)")
    

    is an expression, specifically a function call expression. Wherever that appears, it means the same thing, including an appearance as an argument to the .then() method of a Promise. As in any other similar language, an expression used in a function call is evaluated before the function call, so

    .then(console.log("before 3 seconds (instantly)"))
    

    results in the console.log() function being called first, with the return value then passed to .then(). That's why you see the message in the console immediately.

    Passing undefined to .then() is allowed, and since that's what console.log() returns, there's no error raised.

    If you want that console.log() to happen when the Promise is fulfilled, you'd wrap it in a function:

    .then(function() { console.log("after 3 seconds"); })
    

提交回复
热议问题