DEV Community

Discussion on: Javascript: How to access the return value of a Promise object

Collapse
 
davestewart profile image
Dave Stewart • Edited

It's really important to note that the Promise object doesn't return a value, it resolves a value via the then() method.

It is the fetch() function that returns a value, which is a Promise instance.

It is the Promise instance on which you call the then() method, passing in a callback function, which will be eventually be fired when the async code finishes (and internally, calls resolve()).

As an example, here's what a custom load function might look like:

function load (url) {
  return new Promise(async function (resolve, reject) {
    // do async thing
    const res = await fetch(url)

    // your custom code
    console.log('Yay! Loaded:', url)

    // resolve
    resolve(res.json()) // see note below!
  })
}

// run the function and receive a Promise
const promise = load('https://...')

// let the Promise know what you want to do when it resolves
promise.then(console.log)
Enter fullscreen mode Exit fullscreen mode

Note that the Promise object will resolve any nested promises as part of its work, so resolving res.json() which results in a Promise being created will be resolved internally before the final chained .then(console.log) is called.

The trick to Promises is:

  1. always return Promises you create (or functions that return Promises) so they can be chained
  2. always resolve() or reject() within the promise executor so .then() or .catch() will be called and the chaining will complete
Collapse
 
uzomao profile image
uzoma

Created an account just to say thank you for this breakdown.

Collapse
 
davestewart profile image
Dave Stewart

Well that's very kind of you. I'm glad it helped!