sajad torkamani

What is a JavaScript promise?

A JavaScript promise is a placeholder object for a value you expect to get in the future (e.g., HTTP response from a network call or the result of a slow computation).

Here’s what it looks like:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Promises</title>
  </head>
  <body>
    <h1>Open the browser DevTools</h1>

    <script>
      const promise = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('hello')
        }, 5000)
      })

      // Output the promise before it resolves
      console.log({ 'Promise value before resolving': promise })

      promise
        .then(value => {
          // Output the promise after it resolves
          console.log({ 'Promise value after resolving': promise })
        })
        .catch(error => {
          console.error({ error })
        })
    </script>
  </body>
</html>
Tagged: JavaScript