Async function returning promise, instead of value
An async
function always returns a promise. That's how it reports the completion of its asynchronous work. If you're using it in another async
function, you can use await
to wait for its promise to settle, but in a non-async
function (often at the top level or in an event handler), you have to use the promise directly, e.g.:
latestTime()
.then(time => {
console.log(time);
})
.catch(error => {
// Handle/report error
});
If you're doing this at the top level of a JavaScript module, some environments now support the upcoming top-level await
in modules:
const time = await latestTime();
JavaScript engines are getting support for top-level await
, and Webpack has experimental support for it, for instance.
Here's a rough translation of your async
function in explicit Promise terms:
function latestTime() {
return new Promise((resolve, reject) => {
web3.eth.getBlock('latest')
.then(bl => {
console.log(bl.timestamp);
console.log(typeof bl.timestamp.then == 'function');
resolve(bl.timestamp);
})
.catch(reject);
});
}
Some important notes on that:
- The function you pass to
new Promise
(the promise executor function) gets called synchronously bynew Promise
.- Which is why the operation starts,
web3.eth.getBlock
is called synchronously to start the work.
- Which is why the operation starts,
- Any error (etc.) thrown within the promise executor gets caught by
new Promise
and converting into a promise rejection. - Any error (etc.) thrown within a promise callback (like the one we're passing
then
) will get caught and converted into a rejection.
Function returning promise instead of value - react-native / javascript
You already have a hint - async functions will always return a promise. In order to get the value, you need to wait for it to get fulfilled or rejected. Either use await
or .then()
.
isVoucherClaimed = await isClaimed(voucher.voucherID, uid);
Related Topics
Deleting Array Elements in JavaScript - Delete VS Splice
How to Append Something to an Array
Pretty-Print Json Using JavaScript
Selecting Text in an Element (Akin to Highlighting With Your Mouse)
How Does Data Binding Work in Angularjs
How to Detect Page Zoom Level in All Modern Browsers
Accessing the Web Page'S Http Headers in JavaScript
How to Get Image Size (Height & Width) Using JavaScript
Difference Between a Function Call and Function Reference
Client on Node.Js: Uncaught Referenceerror: Require Is Not Defined
How to Update Nested State Properties in React
Benefits of Using 'Object.Create' For Inheritance
Window.Close and Self.Close Do Not Close the Window in Chrome
Is It an Anti-Pattern to Use Async/Await Inside of a New Promise() Constructor
_Proto_ Vs. Prototype in JavaScript
How to Find Event Listeners on a Dom Node in JavaScript or in Debugging