Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving promises from ES6 Arrow Functions

Reading the docs as I understand it in ES6 the meaning of:

foo => someFun(foo); 

is equivalent to:

foo => { return someFun(foo); }

I'm returning a new Promise and within that code using arrow functions to invoke the resolve & reject methods, e.g.

return new Promise(function(resolve, reject)
{
    someFunThatReturnsAPromise()
    .then(data => resolve(data))
    .catch(err => reject(err));
});

As such is the code in the then actually,

.then(data => return resolve(data))

If so, does it matter that the result of resolve (of which I'm not sure of the type of value) and should I instead be slightly less terse and write it using {} to prevent the implicit return

.then(data => { resolve(data); })
like image 840
const Avatar asked Oct 08 '17 09:10

const


Video Answer


1 Answers

The resolve function already returns undefined, so it makes absolutely no difference if you implicitly return it with a one-line arrow function or don't return it from a function body at all (since the latter means your function body implicitly returns undefined itself).

Furthermore, since you've wrapped the promise returned by someFunThatReturnsAPromise() in a new promise, there's nothing that handles the return anyway so it wouldn't make any difference even if did return something.

More importantly, the way you've wrapped a promise in a new promise is an anti-pattern. The new Promise() construct is only for dealing with asynchronous processes that aren't already promise based.
Since someFunThatReturnsAPromise() already return a promise, you don't need to wrap it in a new one, simply use the one you got!
For your example that would simply mean returning it:

return someFunThatReturnsAPromise()

If you want to do some processing of the data, such as only returning a part of the data (the status property in the below example), you do that in a then callback:

return someFunThatReturnsAPromise().then(data => data.status)

When you return in a then callback, it will in turn return a new promise that gets resolved with the data you returned (unless you returned another promise, in which case it will resolve when that promise resolves).
This is how promises are designed to work, by chaining the asynchronous processes and their results.

like image 127
Lennholm Avatar answered Oct 08 '22 15:10

Lennholm