Search code examples
javascriptreactjsjsonredux

How to get Result from a Promise object?


Working with function which returns Promise object like on the screenshot. How I can get PromiseResult from this object?

Promise object


Solution

  • You can get the result of a promise by using .then() like so:

    functionThatReturnsPromise().then((result) => {
      //do something with result
    })
    .catch(console.error)
    

    Another option is to use async and await like so:

    async function main() {
      const result = await functionThatReturnsPromise()
      // do something with result
    }
    
    main().then(console.log).catch(console.error)
    

    If your environment or compiler supports top-level await you can skip the main wrapper function like so:

    try {
      const result = await functionThatReturnsPromise()
      // do something with result
    }
    catch (err) {
      console.error(err)
    }
    

    Always remember to catch or .catch otherwise you will encounter Unhandled Promise Rejection.