what are promises js 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: .promise()
var promise = new Promise(function(resolve, reject) {
if () {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
Example 3: 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;
}
Example 4: javascript promises
firstRequest()
.then(function(response) {
return secondRequest(response);
}).then(function(nextResponse) {
return thirdRequest(nextResponse);
}).then(function(finalResponse) {
console.log('Final response: ' + finalResponse);
}).catch(failureCallback);