JavaScript Creating Promises
Creating a promise wraps a callback task in a promise. The resolver function takes resolve first and reject second.
Wrap a timer in a promise
The wait helper returns a promise. The timer inside calls resolve, and the then method logs the message.
function wait(ms) {
return new Promise((resolve) => {
setTimeout(() => resolve("Waited " + ms + " ms"), ms);
});
}
wait(50).then((message) => console.log(message));A promise that can fail
The helper takes a flag for success. A false flag calls reject, and the catch logs the error message.
function maybeWork(ok) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (ok) {
resolve("Work done");
} else {
reject(new Error("Work failed"));
}
}, 50);
});
}
maybeWork(false)
.then((message) => console.log(message))
.catch((err) => console.log(err.message));Only the first settle counts
The resolver calls resolve twice with different values. The promise keeps the first value, and the second call changes nothing.
const p = new Promise((resolve) => {
resolve("First");
resolve("Second");
});
p.then((value) => console.log(value));Example
function wait(message, ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(message), ms);
});
}
wait("Step one", 50)
.then((message) => {
console.log(message);
return wait("Step two", 50);
})
.then((message) => console.log(message));Key points
- Resolver: the function passed to new Promise, with resolve and reject as its arguments
- resolve: the function that fulfills the promise with a value
- reject: the function that rejects the promise with an error
- The resolver runs at once, when the promise is built.
- A promise settles only once, so the first call to resolve or reject wins.
- A helper that returns a promise lets any code wait for the task.
In this example, the wait helper wraps a timer in a promise. The chain waits for the first timer, logs its message, and returns a second wait. The chain then waits for the second timer and logs its message.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What order do the resolver arguments come in?