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