Promises combine asynchronous execution with callbacks! Promises run asynchronously and have optional success and failure function arguments.
async
causes a function to return a promise. For example, the following functions are equivalent:
async function myFunc() {
return 'Daltie';
}
async function myFunc2() {
// return Promise.reject('Bad Daltie!'); // Call error function
return Promise.resolve('Daltie'); // Call success function
}
myFunc().then(value =< console.log(value));
myFunc2().then(
value => console.log(value),
error => console.log(error)
);
// Output
// Daltie
// Daltie
await
is used inside of an async
function.
await
waits for Promise
to be fulfilled and returns the results.
Examples here.
Promises can be chained:
async function myFunc() {
return 'Apples!';
}
let success = function (value) {
console.log(value)
return value;
}
myFunc()
.then(success)
.then(success)
.then(success)
.catch(x => console.log(x))
// Output:
// Apples!
// Apples!
// Apples!
Basic syntax:
let myPromise = new Promise(success_func, failure_func) {
// Do stuff, call func(s)
}
myPromise.then(
function(value) { /* Code if successful */ }.
function(error) { /* Code if some error occurs */ }
);
Both the successful and error function are optional.
Basic example:
// Wait 3 seconds, then call myResolve()
let firstPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve('Yay!'); }, 3000);
});
firstPromise.then(function(value) {
console.log(value);
})
// Second promise. Will finish first
let secondPromise = new Promise(function(success, failure) {
if(true) {
success('Success');
} else {
failure('Failure');
}
});
secondPromise.then(
function(value) {console.log(value);},
function(error) {console.log(error);}
);
// Output:
// Success
// Yay!