promises javascript explained code example
Example 1: js create a promise
let promise = new Promise((resolve , reject) => {
fetch("https://myAPI")
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
});
Example 2: 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 3: 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 4: promise js
function tetheredGetNumber(resolve, reject) {
try {
setTimeout(
function() {
const randomInt = Date.now();
const value = randomInt % 10;
try {
if(value >= THRESHOLD_A) {
throw new Error(`Too large: ${value}`);
}
} catch(msg) {
reject(`Error in callback ${msg}`);
}
resolve(value);
return;
}, 500);
} catch(err) {
reject(`Error during setup: ${err}`);
}
return;
}