The JavaScript Promise Object

A Promise Object

According to W3C Schools:

A JavaScript Promise object contains both the producing code and calls to the consuming code.

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

What MDN say:

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

The explanation on the W3C page for the Fetch API gives an example that says that Fetch is based on asyc and await. It then goes on to simplify the explanation, but I found that it didn't really help. The second example actually uses async and wait. There is a third example using "understandable" names for variables.

Links

External Sources

Promise Object - January 2021