[英]Async function returning promise, instead of value
我試圖了解 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 { <pending> }
據我了解, await 應該是阻塞的,並且在上面的代碼中,它似乎會阻塞返回帶有原始timestamp
的 object bl
。 然后,我的 function 返回原始值,但是時間變量設置為待處理的 promise 而不是該原始值。 我錯過了什么?
異步前綴是 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)
})
}
async
函數總是返回一個 Promise。 這就是它報告其異步工作完成的方式。 如果你在另一個async
函數中使用它,你可以使用await
來等待它的 Promise 解決,但是在非async
函數中(通常在頂層或事件處理程序中),你必須直接使用 Promise ,例如:
latestTime()
.then(time => {
console.log(time);
})
.catch(error => {
// Handle/report error
});
如果您在 JavaScript 模塊的頂層執行此操作,一些環境現在支持即將到來的頂層await
in modules :
const time = await latestTime();
JavaScript 引擎正在獲得對頂級await
的支持,例如, Webpack 對它有實驗性的支持。
這是您的async
函數在明確的 Promise 術語中的粗略翻譯:
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);
});
}
關於這一點的一些重要說明:
new Promise
的函數( promise executor函數)被new Promise
同步調用。
web3.eth.getBlock
被同步調用以開始工作。new Promise
捕獲並轉換為 Promise 拒絕。then
)都將被捕獲並轉換為拒絕。無論如何, async
函數都會返回Promise
。 返回值將是`Promise,因此在您的情況下它將是:
async function latestTime(): Promise<some primitive> {
const bl = await web3.eth.getBlock('latest');
return bl.timestamp;
}
因此,您可以進一步使用它的功能,例如:
const time = await latestTime();
但是為了獲得關於async/await
特性的一般視圖,最好閱讀文檔。
簡短的回答:而不是
result = await asyncFunction();
采用:
result = await asyncFunction().then(value => value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.