making promises in js
/*
A Promise is a proxy for a value not necessarily known when the promise is created.
It allows you to associate handlers with an asynchronous action's eventual success
value or failure reason.
*/
let promise = new Promise((resolve , reject) => {
fetch("https://myAPI")
.then((res) => {
// successfully got data
resolve(res);
})
.catch((err) => {
// an error occured
reject(err);
});
});
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*/
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));