我试图了解 async/await 如何与 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 { }
据我了解,await 应该是阻塞的,并且在上面的代码中,它似乎阻止使用原语 timestamp 返回对象 bl 。然后,我的函数返回原始值,但是时间变量设置为待处理的承诺而不是该原始值。我错过了什么?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
异步前缀是 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; }与相同
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) }) }