get value from promise when settled or rejected js code example
Example 1: promise javascript
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
Example 2: javascript promises
var posts = [
{name:"Mark42",message:"Nice to meet you"},
{name:"Veronica",message:"I'm everywhere"}
];
function Create_Post(){
setTimeout(() => {
posts.forEach((item) => {
console.log(`${item.name} --- ${item.message}`);
});
},1000);
}
function New_Post(add_new_data){
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(add_new_data);
var error = false;
if(error){
reject("Something wrong in >, Try setting me TRUE and check in console");
}
else{
resolve();
}
},2000);
})
}
New_Post({name:"War Machine",message:"I'm here to protect"})
.then(Create_Post)
.catch(err => console.log(err));