0
Q:

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);
    });          
});
5
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 */ }
);
29
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*/
14
getData()
    .then(data => console.log(data))
    .catch(error => console.log(error));
1
firstRequest()
  .then(function(response) {
    return secondRequest(response);
}).then(function(nextResponse) {  
    return thirdRequest(nextResponse);
}).then(function(finalResponse) {  
    console.log('Final response: ' + finalResponse);
}).catch(failureCallback);
0
function getData() {
    return new Promise((resolve, reject)=>{
        request( `http://www.omdbapi.com/?t=The+Matrix`, (error, res, movieData)=>{
            if (error) reject(error);
            else resolve(movieData);
        });
    });
}
0
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));
0

New to Communities?

Join the community