DEV Community

Discussion on: Retrieving Data from Promise: then() & catch()

Collapse
 
askindzer profile image
Andrei Skindzer • Edited

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

Collapse
 
swarnaliroy94 profile image
Swarnali Roy • Edited

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:

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
    }).then(()=>{
    console.log(a)
})
//console.log(a);
Enter fullscreen mode Exit fullscreen mode

or

addition(2,5).then((response)=>{
a=response
})
setTimeout(() => console.log(a), 0);
Enter fullscreen mode Exit fullscreen mode

Depending on your need, you can look at closures in JS to learn more.
Hope this works