On my journey of learning Promises in Javascript/Nodejs, I came a cross an issue while working on some code so I made a sample of my problem below. First, I have a calculation that takes a long time but at some point I need the answer before I can continue on with the rest of code. (On a side note, I am new to Javascript/Nodejs)
function add(x,y) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("1 + 1 =", x+y );
resolve(x + y);
}, 300);
});
}
function calc(x,y)
{
let answer;
let promise = add(x,y);
promise.then(function (value) {
console.log("1 + 1 =", answer );
answer = value;
});
return answer;
}
console.log('Calculation of 1 + 1 =', calc(1,1)); // I need an answer here. If I have to wait, so be it!
console.log('The correct answer is ',1+1);
console.log('The end.');
The Output
----------
Calculation of 1 + 1 = undefined
The correct answer is 2
The end.
1 + 1 = 2
1 + 1 = undefined