xxxxxxxxxx
new Promise((resolve, reject) => {
console.log('Initial');
resolve();
})
.then(() => {
throw new Error('Something failed');
console.log('Do this');
})
.catch(() => {
console.error('Do that');
})
.then(() => {
console.log('Do this, no matter what happened before');
});
xxxxxxxxxx
let conditions=true;
const proms= new Promise((resolve, reject) => {
setTimeout(() => {
if (conditions) {
resolve ("Hello")
} else {
reject ("This condition faild")
}
}, 2000);
});
proms.then((result) => {
console.log(result);
})
.catch(function(error){
console.log(error);
});
xxxxxxxxxx
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 */ }
);
xxxxxxxxxx
let promise = new Promise((resolve,reject)=>{
try {
resolve("some data");
} catch (error) {
reject(error);
}
})
promise.then(function (data) {
console.log(data);
},function (error) {
console.error(error);
})
xxxxxxxxxx
const fetchData = () => {
fetch('https://api.github.com').then(resp => {
resp.json().then(data => {
console.log(data);
});
});
};
xxxxxxxxxx
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)
})
xxxxxxxxxx
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"
xxxxxxxxxx
const executorFunction = (resolve, reject) => {
if (someCondition) {
resolve('I resolved!');
} else {
reject('I rejected!');
}
}
const myFirstPromise = new Promise(executorFunction);
xxxxxxxxxx
const prom = new Promise((resolve, reject) => {
resolve('Yay!');
});
const handleSuccess = (resolvedValue) => {
console.log(resolvedValue);
};
prom.then(handleSuccess); // Prints: 'Yay!'
xxxxxxxxxx
/*
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) => {
});