Promise - `then()` not works as expect

2019-02-19 19:47发布

问题:

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

回答1:

.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));