Skip to content Skip to sidebar Skip to footer

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)=>

Solution 1:

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.

Solution 2:

It is easier to illustrate this via examples. Your first case:

constfn = (text) => {console.log(text)}

constwaiter = () => newPromise((resolve, reject) => {
  returnsetTimeout(() => {
    fn('resolved')
    resolve()
  }, 2000)
})

waiter().then(fn('done'))

Notice that fn got executed first, got evaluated and then the waiter got executed.

Lets look at the 2nd case:

constfn = (text) => {console.log(text)}

constwaiter = () => newPromise((resolve, reject) => {
  returnsetTimeout(() => {
    fn('resolved')
    resolve()
  }, 2000)
})

waiter().then(() =>fn('done'))

Notice now that we got resolved first and then done.

So the answer to your question is yes in both cases we will wait and execute the someFunc or in the above example the waiter.

The main difference really is when does your dosomethingafter get executed.

In the first case it is right away and then it is passed in the waiter.

In the second case you have a valid promise chain which will first be executed and then once done (and since fn acts as the function handler of the then) it will execute dosomethingafter.

Solution 3:

pass doSomethingafter first class

consthandleAsJson = response => response.json()
fetch(url)
  .then(handleAsJson)
  .then(console.log)

Post a Comment for "Javascript Then Without Promise Return Val"