Promise - `then()` not works as expect

一世执手 提交于 2021-02-04 19:43:06

问题


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


来源:https://stackoverflow.com/questions/49606585/promise-then-not-works-as-expect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!