return Promise 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: 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: 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: .promise()
var promise = new Promise(function(resolve, reject) {
if () {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
Example 5: return new Promise(res => {
new Promise((resolve, reject) => {
throw new Error("Whoops!");
}).catch(function(error) {
alert("The error is handled, continue normally");
}).then(() => alert("Next successful handler runs"));
Example 6: var fn = () => { return new Promise(r => r(5)) }
var fn = () => {
return new Promise(r => r(5))
}