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 primitivetimestampto 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.
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; }the same with
function latestTime() { return new Promise(function(resolve,success){ const bl = web3.eth.getBlock('latest'); bl.then(function(result){ console.log(result.timestamp); // Returns a primitive console.log(typeof result.timestamp.then == 'function'); //Returns false - not a promise resolve(result.timestamp) }) }asyncFunctions always return a Promise. This is how it reports the completion of asynchronous work. If you're using it inside anotherasyncfunction, you can useawaitto wait for its promise to resolve, but in a non-asyncfunction (usually at the top level or in an event handler), you have to use Promise directly, for example:latestTime() .then(time => { console.log(time); }) .catch(error => { // Handle/report error });...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/catchHandles 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
asyncfunction under the hood: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:
new Promise(thepromise executorfunction) is called synchronously bynew Promise.web3.eth.getBlocksynchronously to start the work.new Promiseand converted into a Promise rejection.thenerrors we pass) will be caught and converted into rejections.