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 */ }
);
let promise = new Promise(function(resolve, reject){
try{
resolve("works"); //if works
} catch(err){
reject(err); //doesn't work
}
}).then(alert, console.log); // if doesn't work, then console.log it, if it does, then alert "works"
/*
Promise is a constructor function, so you need to use the new keyword to
create one. It takes a function, as its argument, with two parameters -
resolve and reject. These are methods used to determine the outcome of the
promise.
The syntax looks like this:
*/
const myPromise = new Promise((resolve, reject) => {
});
let num = 10;
//call back function
const promis = new Promise(function (resolve, reject) {
if (num > 5) {
//this resolve method will send data to resoleveData variable
resolve(" Problem resolved successfully")
}
else {
//this reject method will send data to rejectData variable
reject("sorry problem couldn't solve")
}
})
//resoleveData variable
promis.then(function (resolveData) {
console.log(resolveData)
//rejectData variable
}).catch(function (rejectData) {
console.log(rejectData)
})
const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
resolutionFunc(777);
});
// At this point, "promiseA" is already settled.
promiseA.then( (val) => console.log("asynchronous logging has val:",val) );
console.log("immediate logging");
// produces output in this order:
// immediate logging
// asynchronous logging has val: 777
let num = 2;
//call back function
const promis = new Promise(function (resolve, reject) {
if (num > 5) {
//this resolve method will send data to resoleveData variable
resolve(" Problem resolved successfully")
}
else {
//this reject method will send data to rejectData variable
reject("sorry problem couldn't solve")
}
})
promis.then(
//resoleveData variable
function (resolveData) {
console.log(resolveData)
}).catch(
//rejectData variable
function (rejectData) {
console.log(rejectData)
})
let dataIsLoading = true;
promise
.then(data => {
// do something with data
})
.catch(error => {
// do something with error
})
.finally(() => {
dataIsLoading = false;
})