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:
- pending: the result isn't known yet.
- fulfilled: it finished well, with a value.
- rejected: it failed, with an error.
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));
.then(fn)runs if the promise is fulfilled..catch(fn)runs if it is rejected.- You can chain several
.thencalls, returning a value at each step.
In the practices, the checker waits for your promises to resolve (it uses
awaitinternally), 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);