Mark
Mark

Reputation: 11

ECMAScript 6 promises

I'd like understand promises, but I have problem.

function commentFirst() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('first');
      resolve('value');
    }, 1500);
  });
}

commentFirst().then((val) => {
  setTimeout(function() {
    console.log(val + ' 1')                   
  }, 2000);

  return val;
}).then((val1) => console.log(val1 + ' 2'));

I want get output like this:

first
value 1
value 2

What am I doing wrong?

Upvotes: 1

Views: 182

Answers (2)

Paul Boutes
Paul Boutes

Reputation: 3315

You can improve your code by creating multiple promise, to make your code more reusable.

So, you will be able to chain your promise.

But, you should see the Promise.all() method which allow you to returns a promise that resolves when all of the promises in the iterable argument have resolved.

You can decalre two function which will return some promise :

function first(){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('first');
    }, 1000);
  });
}

function commentFirst(id){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('value ' + id);
    }, 1000);
  });
}

Then, you've got two options :

  • Option 1 : Perform a chaining promise
  • Option 2 : Use the Promise.all() method

Option 1 : chaining

first().then((data) => {
  //Log first
  console.log(data);
  //Return promise to print value 1
  return commentFirst(1);
}).then((data) => {
  //Log value 1
  console.log(data);
  //Return promise to print value 2
  return commentFirst(2);
}).then((data) => {
  //log value 2
  console.log(data);
});

Option 2 : Promise.all()

Promise.all([first(), commentFirst(1), commentFirst(2)]).then((data) => {
  data.forEach((elm) => console.log(elm));
});

As you can see, option 2 is shorter than option 1. In fact, the .all() method is used to handle multiple promise, and return a single promise with all the results.

Upvotes: 0

Georgette Pincin
Georgette Pincin

Reputation: 292

In the second .then, you are doing a setTimeout without any promise, so it will execute and return immediately, even before the setTimeout executes. I've added a promise such that when the setTimeout executes, it will resolve the promise, and then continue executing the order you need.

function commentFirst() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('first');
      resolve("value");
    }, 1500);
  });
}

commentFirst()
  .then((val) => {
    return new Promise(resolve => {
      setTimeout(function() {
        console.log(val + ' 1')
        resolve(val);
      }, 2000);
    })
  })
  .then((val1) => console.log(val1 + ' 2'));

codepen demo

Upvotes: 3

Related Questions