Search code examples
javascriptecmascript-6promisees6-promise

Javascript then without promise return val


Perhaps i'm not googleing correctly. does a then function without a paramater not block? for instance, you have a promise:

someFunc = () => {
  return new Promise((res,rej)=>{
   somethingAsync(input).then((val) => res(val))
  })
}

in the following implements of our function. would both wait for the someFunc return val?

someFunc().then(dosomethingafter())
someFunc().then((val) => dosomethingafter())

Solution

  • In JS expressions are eagerly evaluated. It means every function argument is evaluated before it's passed.

    someFunc().then(dosomethingafter())
    

    is effectively identical to

    var tmp = dosomethingafter();
    someFunc().then(tmp)
    

    so a function someFunc().then(dosomethingafter()) is invoked before then is called, and its returned result is passed as a parameter.

    What you probably meant instead is

    someFunc().then(dosomethingafter)
    

    note there is no function call - only a reference to a function is passed to then and it would then be called when a promise is resolved.