2

This is a piece of code I wrote. I have trouble accessing data from Promise for later purposes.

function forgotPassword(params) {
  return new Promise(function (resolve, reject) {
    return client.methodCall('forgotPassword', params, function (error, value) {
      if (error === null) {
        if (value === true) {
          console.log('Password Sent!!');
          //subpy.kill('SIGINT');
          return resolve('Password Sent!!');
        }
        else {
          console.log('User Not Found!!');
          //subpy.kill('SIGINT');
          return resolve('User Not Found!!');
        }
      }
      else {
        console.log('Error while doing the Operation!!');
        //subpy.kill('SIGINT');
        return reject(error);
      }
    });
  }
  );
}
halfer
  • 19,824
  • 17
  • 99
  • 186
TheGhoul27
  • 29
  • 3
  • what is data here ? – Balaji Nov 06 '21 at 11:05
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Nov 07 '21 at 07:27
  • @DankDizaster The data here is whether the password is sent to the respective mail id or no. I have returned a specific value to the function. I'm trying to store the value from Promise for later purposes but I'm not able to. – TheGhoul27 Nov 08 '21 at 03:09

1 Answers1

1

I suggest you read the docs on Async Functions and Promises.

In this case you can do a few things

new Promise(function (resolve, reject) {
    return client.methodCall('forgotPassword', params, function (error, value) {
      if (error === null) {
        if (value === true) {
          console.log('Password Sent!!');
          //subpy.kill('SIGINT');
          return resolve('Password Sent!!');
        }
        else {
          console.log('User Not Found!!');
          //subpy.kill('SIGINT');
          return resolve('User Not Found!!');
        }
      }
      else {
        console.log('Error while doing the Operation!!');
        //subpy.kill('SIGINT');
        return reject(error);
      }
    });
  })
.then(res => console.log(res))
.catch(rej => console.log(rej));

The then will be called if the resolve is called.

The catch will be called if there is an error or reject is called.

Another way is to use await inside a async function to wait until you get a result from the promise object

function myPromiseFunction(){
    return new Promise(function (resolve, reject) {.....
}

async function myfunction() {
  try {
      var res = await myPromiseFunction(); // waits until result from promise
      console.log(res);
  } catch (error){
      console.log(error);
  }
  
}

myfunction();
Balaji
  • 795
  • 1
  • 2
  • 10