I'm trying to understand how async/await works with Promise.
async function latestTime() { const bl = await web3.eth.getBlock('latest'); console.log(bl.timestamp); // Returns a primitive console.log(typeof bl.timestamp.then == 'function'); //Returns false - not a promise return bl.timestamp; } const time = latestTime(); // Promise {}
From what I understand, await is supposed to be blocking, and in the code above, it seems to prevent using the primitivetimestamp
to return an objectbl
. My function then returns the original value, but the time variable is set to the pending promise instead of that original value. What did I miss?
Asynchronous prefix is a wrapper for Promises.
the same with
async
Functions always return a Promise. This is how it reports the completion of asynchronous work. If you're using it inside anotherasync
function, you can useawait
to wait for its promise to resolve, but in a non-async
function (usually at the top level or in an event handler), you have to use Promise directly, for example:...However, if you do this at the top level of a JavaScript module, all modern environments now support top-levelawait
inmodules:
(Note that if this Promise is rejected, your module will fail to load. If your module works meaningfully even if the Promise fails, be sure to wrap it in a
try
/catch
Handles promise rejection.)Itmay(or may not) reveal something in the form of explicit promise callback terms that gives us an idea of how the JavaScript engine handles your
async
function under the hood:Some important notes:
new Promise
(thepromise executorfunction) is called synchronously bynew Promise
.web3.eth.getBlock
synchronously to start the work.new Promise
and converted into a Promise rejection.then
errors we pass) will be caught and converted into rejections.