Promise () javacsript code example
Example 1: javascript promise
var promise = new Promise(function(resolve, reject) {
// do some long running async thing…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
//usage
promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
Example 2: Promise
let doSecond = () => {
console.log('Do second.')
}
let doFirst = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Do first.')
resolve()
}, 500)
})
doFirst.then(doSecond)