Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get resolved data from a Promise

Consider the following code snippet:

let primise = new Promise((resolve, reject) => {
    resolve({ x: 10 });
});

setTimeout(() => {
  // At some moment in the future (Promise is resolved)
    console.log(promise);
}, 200);

Now, the promise was resolved with { x: 10 }. How do I access this data using the resolved promise ?

Inspecting the promise object I can see the data is available as promise._v but this doesn't look right. Any help would be appreciated

like image 653
Jeanluca Scaljeri Avatar asked Sep 19 '25 03:09

Jeanluca Scaljeri


1 Answers

No, you cannot inspect promises (at least not native promises, some userland implementations do have synchronous inspection methods available).

So - as always - use promise.then(v => console.log(v)). Only then you can be sure that the promise is fulfilled.

If you also want to wait 200ms, use another promise for the timeout and Promise.all to wait for both of them:

let promise = Promise.resolve({ x: 10 });

Promise.all([promise, new Promise(resolve => setTimeout(resolve, 200))]).then([v] => {
    // At some moment in the future (and promise is fulfilled)
    console.log(v); // {x: 10}
});
like image 116
Bergi Avatar answered Sep 20 '25 16:09

Bergi