how to get value from javascript promise?

2019-03-06 16:09发布

问题:

I have a userBalance promise object with following values:

> userBalance
Promise {
'100000000000000000',
domain:
 Domain {
   domain: null,
   _events:
    { removeListener: [Function: updateExceptionCapture],
      newListener: [Function: updateExceptionCapture],
      error: [Function: debugDomainError] },
   _eventsCount: 3,
   _maxListeners: undefined,
   members: [] } }

the problem is, i cannot get that 100000000000000000 from it. is there a way to do so?

回答1:

The only way to get the resolution value of a promise (even if it's already resolved) is to consume the promise, via then or await:

userBalance.then(value => {
    // ...use `value`; note this will be called asynchronously
});

or in an async function:

const value = await userBalance; // Note this will be asynchronous

In both cases, plus error handling unless you're passing the resulting promise onto something else that will handle it.