Is there a way to save data in another variable, not a Promise but resolved value?
Ex:
const addition = (a, b) =>
new Promise((resolve, reject) => {
if (typeof a == "number" && typeof b == "number") {
resolve(a + b);
} else {
reject ("Not a Number")
}
});
The example that you've given won't work as when you are assigning a, it's value is 'undefined' and the console.log(a) will be undefined at the time of execution because, it is delayed by the promise and pushed to the event queue.
If you want to access the changed value , you need to follow up with another then or do something that put your code in the event queue after the assignment.
Ex:
constaddition=(a,b)=>newPromise((resolve,reject)=>{if(typeofa=="number"&&typeofb=="number"){resolve(a+b);}else{reject("Not a Number")}});leta;addition(2,5).then((response)=>{a=response}).then(()=>{console.log(a)})//console.log(a);
Is there a way to save data in another variable, not a Promise but resolved value?
Ex:
const addition = (a, b) =>
new Promise((resolve, reject) => {
if (typeof a == "number" && typeof b == "number") {
resolve(a + b);
} else {
reject ("Not a Number")
}
});
let a;
addition(2,5).then((response)=>{
a=response
});
console.log(a);
// Output:
// underfined
The example that you've given won't work as when you are assigning a, it's value is 'undefined' and the console.log(a) will be undefined at the time of execution because, it is delayed by the promise and pushed to the event queue.
If you want to access the changed value , you need to follow up with another then or do something that put your code in the event queue after the assignment.
Ex:
or
Depending on your need, you can look at closures in JS to learn more.
Hope this works