DevPath · Learn to code ESPTEN

Asynchrony: promises and async/await

Promises

What is a promise?

A promise (Promise) is an object that represents the result of an operation that hasn't finished yet. A promise is in one of three states:

const promise = new Promise((resolve, reject) => {
  const success = true;
  if (success) {
    resolve("Data ready!"); // fulfilled
  } else {
    reject(new Error("Failed")); // rejected
  }
});

Consuming a promise: then and catch

promise
  .then((value) => console.log("Success:", value))
  .catch((error) => console.log("Error:", error.message));

In the practices, the checker waits for your promises to resolve (it uses await internally), so it will check both the structure of your code and the final value it produces. What you write will be real asynchronous code.

Examples

Create and consume a promise

function quickTask(ok) {
  return new Promise((resolve, reject) => {
    if (ok) resolve("done");
    else reject(new Error("failure"));
  });
}
quickTask(true).then((v) => console.log("Result:", v));
console.log("Is it a promise?", quickTask(true) instanceof Promise);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← The event loop and callbacksasync / await and Promise.all →