-2

My Codes below;

I've a then-catch block. My responseArray is a global variable. i got response from functionName function; but i can't use result out of then block. How can i use then response out of block?

My Codes below;

I've a then-catch block. My responseArray is a global variable. i got response from functionName function; but i can't use result out of then block. How can i use then response out of block?

module.exports = {
 foo1: function(param){
   return new Promise((resolve,reject) => {
      var result = //some code here
      resolve(result);
   });
 },
 foo2: function(param){
   return new Promise((resolve,reject) => {
      this.foo1('abc').then(function(res){
        let response = {
            'item':'ok',
            'result':res.some_field
        };
        console.log(response);  // its ok here. 
        responseArray.push(response); //its ok here too
    }).catch(err =>{
        console.log(err);
        reject(err);
    });
    console.log(responseArray); //nothing in array here
    resolve(responseArray);
   });
 }
};
bayboran
  • 25
  • 5
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance May 20 '19 at 11:57
  • and https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – CertainPerformance May 20 '19 at 11:57

1 Answers1

0

First thing to remember is that promises are asynchronous. Promises are doing exactly what they say, you are essentially signing a contract (promise) that you will get your data (or error) but not synchronously, but at some time in the future when the computations have finished.

In order to access your responseArray you will need to resolve your foo2 promise (inside of .then) and continue the promise chain by calling it, i.e.

module.exports = {
 foo1: function(param){
   return new Promise((resolve,reject) => {
      var result = //some code here
      resolve(result);
   });
 },
 foo2: function(param){
   return new Promise((resolve,reject) => {
      this.foo1('abc').then(function(res){
        let response = {
            'item':'ok',
            'result':res.some_field
        };
        console.log(response);  // its ok here. 
        responseArray.push(response); //its ok here too
        resolve(responseArray) // resolve the promise inside of .then
    }).catch(err =>{
        console.log(err);
        reject(err);
    });
   });
 }
};

foo2('someValue').then(response => {
  console.log(response) // this will be your array
})

Also, as a side note, ensure you are not falling into the trap of the promise constructor anti-pattern. This is where you unnecessarily turn synchronous code into asynchronous code just for the sake of using "promises"

For example, a valid use of a promise would be to convert a callback, like so:

const getFile = filename => {
  return new Promise((resolve, reject) => {
    fs.readFile(filename, 'utf8', (err, data) => {
      if (err) reject(err)
      resolve(data)
    })
  })
} 

whereas this is unnecessary:

const printData = data => {
  return new Promise((resolve, reject) => {
    resolve(console.log(data))
  })
} 

vs

const printData = data => {
  console.log(data)
}

Read more here: What is the explicit promise construction antipattern and how do I avoid it?

Matt Kent
  • 1,145
  • 1
  • 11
  • 26