问题
I'm trying to understand how async/await works in conjunction together with promises.
Code
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 { <pending> }
Issue
As far as I understand, await should be blocking and in the code above it seemingly blocks returning an object bl
with the primitive timestamp
. Then, my function returns the primitive value, however the time variable is set to a pending promise instead of that primitive. What am I missing?
回答1:
Async prefix is a kind of 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;
}
Is the same as
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)
})
}
回答2:
async
function will return Promise
anyway. Return value will be `Promise, so in your case it will be:
async function latestTime(): Promise<some primitive> {
const bl = await web3.eth.getBlock('latest');
return bl.timestamp;
}
So, further you can use it function like:
const time = await latestTime();
But for achieving general view about async/await
feature it will be better to read documentation.
来源:https://stackoverflow.com/questions/51338277/async-function-returning-promise-instead-of-value