return promise result 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 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 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();
});
}
Example 4: js promiseStatus
function MakeQuerablePromise(promise) {
if (promise.isResolved) return promise;
var isPending = true;
var isRejected = false;
var isFulfilled = false;
var result = promise.then(
function(v) {
isFulfilled = true;
isPending = false;
return v;
},
function(e) {
isRejected = true;
isPending = false;
throw e;
}
);
result.isFulfilled = function() { return isFulfilled; };
result.isPending = function() { return isPending; };
result.isRejected = function() { return isRejected; };
return result;
}