what does a promise return code example
Example 1: javascript return promise
function doSomething() {
return new Promise((resolve, reject) => {
console.log("It is done.");
if (Math.random() > .5) {
resolve("SUCCESS")
} else {
reject("FAILURE")
}
})
}
const promise = doSomething();
promise.then(successCallback, failureCallback);
Example 2: promise catch
var p1 = new Promise(function(resolve, reject) {
resolve("Success");
});
p1.then(function(value) {
console.log(value);
throw "oh, no!";
}).catch(function(e) {
console.log(e);
});
Example 3: js return a promise
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}