Console Learner — An interactive JavaScript course.


5.3 Promises

>>>
Promise.resolve(42)
Promise(status="fulfilled", result=42)
Using Promise.resolve() creates a new promise that immediately resolves with a value.
>>>
new Promise(function (resolve, reject) {
    resolve(42);
})
Promise(status="fulfilled", result=42)
The more complicated new Promise() constructor can achieve the same result. The constructor calls a supplied function with callbacks for either resolving or rejecting the promise.
>>>
Promise.resolve(42)
    .then((v) => v + 58)
    .then(print);

  
The then(), catch() and finally() methods attaches callbacks to handle results or errors, analogous to how exceptions are managed. Each of these return a new promise that resolves when both the original promise and the callback has finished.
>>>
new Promise(function (resolve, reject) {
    throw new TypeError('oops!')
})
Promise(status="rejected", result=TypeError("oops!"))
Promises are automatically rejected if an operation or callback throws an error. A similar result can be obtained with return Promise.reject(...) from any callback.
>>>
function wait(millis, value) {
    if (arguments.length < 2) {
        return wait.bind(null, millis);
    } else {
        return new Promise(function (resolve, reject) {
            setTimeout(() => resolve(value), millis);
        });
    }
}

  
Similar to the previous callLater() function, this helper wraps setTimeout() for usage with promises.
>>>
Promise.resolve('done!')
    .then(wait(1000))
    .then(print);

  
The wait(1000) call above returns a partially bound version of wait() that is called as the promise is resolved.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.