Reputation: 29097
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
Upvotes: 4
Views: 12256
Reputation: 664195
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}
});
Upvotes: 4
Reputation: 2690
The whole point of a promise is so that you don't have to wait an arbitrary amount of time to determine whether the promise is resolved... you just hook into it.
let promise = new Promise((resolve, reject) => {
resolve({ x: 10 });
});
...
promise.then(data => {
// use data here...
});
Upvotes: 3