3gwebtrain
3gwebtrain

Reputation: 15303

Promise - `then()` not works as expect

I do have 2 function. I am chaining with then() method for promise. But I am trying to initiate the second function after the first promise happend. But now the second function call as first. how to fix this?

or any issue with my code?

here is my try:

var getData = function(){
    return new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(42); //consoles as second
    }, 5000);
  })
}

var getDataMoreData = function(){
    return new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(43); //consoles as first
    }, 3000);
  })
}



getData().then((data)=> console.log('Data', data)).then(getDataMoreData().then((data)=> console.log('data--', data )));

Live Demo

Upvotes: 2

Views: 152

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371138

.then accepts a function as a parameter. When you do

.then(getDataMoreData()
  .then((data) => console.log('data--', data))
);

, it immediately calls getDataMoreData() (with the expectation that it will return a function that it can put into the promise chain). But getDataMoreData does not return a function - it returns a promise.

Any function calls immediately within a then get executed immediately, as it attempts to build the .then promise chain. Simply list the function variable inside the then instead of calling it:

var getData = function() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(42); 
    }, 500);
  })
}

var getDataMoreData = function() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(43); 
    }, 300);
  })
}



getData()
  .then((data) => console.log('Data', data))
  .then(getDataMoreData)
  .then((data) => console.log('data--', data));

Upvotes: 7

Related Questions