简体   繁体   中英

Returning promises up?

I was reading about javascript in MDN and came across this part that talks about promises and did not understand what it meant.

The code is pretty straight forward however I do not understand the word of caution. What does it mean to return promises up? What does it mean to return implicitly? If its a dumb question please point to some resource and I'll mark it as closed.

doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);

Important: Always return promises up, otherwise callbacks won't chain, and errors won't be caught (arrow functions return implicitly when {} are left out).

Return a promise up usually mean to be able to chain another .then .

Here you are not returning anything:

.then(finalResult => {
  console.log(`Got the final result: ${finalResult}`);
})

So you can't chain another .then after it.

Edit
As mentioned in the comments, .then actually always returns another promise.
But there is a catch, if your resolve callback won't return anything ( undefined ) then the caller of this promise will get undefined as the parameter.
So basically there is no gain in just chain "empty" then .

Here is a small running example of such case:

 const promise = new Promise((resolve, reject) => { resolve("#1"); }); promise .then((result) => result) .then((result) => `${result} #2`) .then((result) => console.log(result)) .then((result) => `${result} #4`) // <-- result === undefined .then((result) => console.log(result)) .then((result) => console.log(result)) .then((result) => '#7') .then((result) => console.log(result)); 


As for this statement:

arrow functions return implicitly when {} are left out

Arrow functions can return in 2 ways:

implicit:

const func = () => {'hi there'} // nothing is returned

But when there is a body for the function {} nothing is returned:

 const func = () => {'hi there'} // nothing is returned 

explicitly :

When we use the return key word:

const func = () => {a:1} // nothing is returned, just a meaningless label a

Gotchas:
Sometimes you want to return an object, so there is a common mistake that people do:

const func = () => ({ a:1 }) // implicitly returns an object

So a "fix" for that is to wrap the object with an expression:

 const func = () => ({ a:1 }) // implicitly returns an object 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM