skip to Main Content
function getSmth(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(num * num), 500)
  });
}
function func() {
  getSmth(2).then(res1 => {
    getSmth(3).then(res2 => {
      getSmth(4).then(res3 => {
        console.log(res1 + res2 + res3);
      });
    });
  });
}
   func();
function getSmth(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(num * num), 500)
  });
}
function func() {
  getSmth(2)
    .then(res1 => getSmth(3))
    .then(res2 => getSmth(4))
    .then(res3 => {
      console.log(res1 + res2 + res3);
    })
}
func();

Should output 29 to the console but it’s not work.

2

Answers


  1. As others have mentioned before me the issue with your chaining is that you are losing the context of the previous result. So you can either use async/await or Promise.all

    Here is the async/await syntax which leaves the code more readable

    function getSmth(num) {
      return new Promise((resolve, reject) => {
        setTimeout(() => resolve(num * num), 500)
      });
    }
    
    async func(){
      const res1 = await getSmth(2);
      const res2 = await getSmth(3); 
      const res3 = await getSmth(4);
      console.log(res1 + res2 +res3);
    }
    
    func().then(()=>{})
    

    You can also use Promise.all like this

    
    Promise.all([getSmth(2), getSmth(3), getSmth(4)])
    .then( results => console.log(results[0] + results[1] + results[2]);
    
    
    Login or Signup to reply.
  2. If you want to use async/await other answers show the correct code. I think what you might be trying to get is:

    function func() {
      getSmth(2)
        .then(result => getSmth(3).then(res2 => result + res2))
        .then(result => getSmth(4).then(res3 => result + res3))
        .then(result => {
          console.log(result);
        })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search