handle promise in javascript code example
Example 1: javascript promise
var promise = new Promise(function(resolve, reject) {
if () {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(
function(result) { },
function(error) { }
);
Example 2: javascript create promise
const promise = new Promise(executor);
const coinflip = (bet) => new Promise((resolve, reject) => {
const hasWon = Math.random() > 0.5 ? true : false;
if (hasWon) {
setTimeout(() => {
resolve(bet * 2);
}, 2000);
} else {
reject(new Error("You lost..."));
}
});
Example 3: .promise()
var promise = new Promise(function(resolve, reject) {
if () {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});