Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())
like image 469
Jeremy Nelson Avatar asked Jun 10 '26 09:06

Jeremy Nelson


1 Answers

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.

like image 82
zerkms Avatar answered Jun 11 '26 23:06

zerkms