简体   繁体   中英

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)

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.

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