Probosckie
Probosckie

Reputation: 1812

Javascript returning promises with then callbacks

I have recently seen this kind of pattern in a book -> What is the value (data-type) being returned from a function if I return a Promise along with it's then callback:

function combineValues(p1,p1){
   return Promise.all([p1,p2])
           .then((d) => {
              return transformData(d);
           }
}

How can the return value of the above function combineValues be a promise?? We are already adding a .then at the end of something that is being returned.

And yet - below this code it was written

let p1 = fetch('url1'), p2 = fetch('url2');
combineValues(p1,p2)
  .then(v => console.log(`combined value is ${v}`))

If the 1st code snippet was only returning - Promise.all([p1,p2]) - then the 2nd code snippet is understandable - but it's returning

Promise.all([p1,p2]).then(something)

Upvotes: 0

Views: 50

Answers (1)

Quentin
Quentin

Reputation: 944528

then always returns a promise, by definition (and it couldn't return the resolved value: The resolved value doesn't exist at the time the code the return value is being passed to is running).

In the second example, you aren't looking at the return value of then, you are logging inside the callback.

Upvotes: 1

Related Questions