Using Promises
What are promises?
A Promise
is an object, representing the eventual completion or failure of an asynchronous operation.
why?
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
One of the great things about using promises is chaining.
- Multiple callbacks may be added by calling
then()
several times. They will be invoked one after another, in the order in which they were inserted.
Promise.all()
and Promise.race()
are two composition tools for running asynchronous operations in parallel.
Promise.all([func1(), func2(), func3()])
.then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ });const promise = new Promise(function(resolve, reject) {
console.log(“Promise callback”);
resolve();
}).then(function(result) {
console.log(“Promise callback (.then)”);
});setTimeout(function() {
console.log(“event-loop cycle: Promise (fulfilled)”, promise)
}, 0);console.log(“Promise (pending)”, promise);
output will be
“Promise callback”
“Promise (pending)”
[object Promise] { … }
“Promise callback (.then)”
“event-loop cycle: Promise (fulfilled)”
[object Promise] { … }