js return a promise
var promise = new Promise(function(resolve, reject) {
// do some long running async thing…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
//usage
promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
const p1 = new Promise((resolve, reject) => {
console.log("Promise has started");
const lifeIsEasy = false;
if (lifeIsEasy) {
//Value to be returned if the promise is resolved
//return value is optional
resolve("No it's not");
}
else {
//Value to be returned if the promise is rejected
//return value is also optional
reject("welcome to the real world");
}
});
//then is executed when the promise is resolved
p1.then(value => {
console.log(value);
})
//catch is executed when the promise is rejected
.catch (err => {
console.log(err);
});
/*expected output
Promise has started
welcome to the real world*/