how do promises work js 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: 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;
}