異步函數不返回值,但是控制臺日志()做:如何做?我有ES6課程init()方法負責獲取、轉換數據,然后更新類的屬性this.data新轉換的數據。到目前一切尚好。這個類本身有另一個getPostById()方法,只做聽起來像的事。下面是這個類的代碼:class Posts {
constructor(url) {
this.ready = false
this.data = {}
this.url = url }
async init() {
try {
let res = await fetch( this.url )
if (res.ok) {
let data = await res.json()
// Do bunch of transformation stuff here
this.data = data this.ready = true
return data }
}
catch (e) {
console.log(e)
}
}
getPostById(id){
return this.data.find( p => p.id === id )
}}直截了當,除了我有一個async/await機制init()方法。現在,此代碼將正確工作:let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')allPosts.init()
.then( d => console.log(allPosts.getPostById(4)) )// resulting Object correctly logged in console但是它只會被打印到控制臺上:我如何使用allPosts.getPostById(4)作為return某項功能?比如:let myFunc = async () => {
const postId = 4
await allPosts.init() // I need to wait for this to finish before returning
// This is logging correct value
console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )
// How can I return the RESULT of allPosts.getPostById( postId ) ???
return allPosts.getPostById( postId )}myFunc()返回Promise但不是最終價值。我讀過幾篇關于這一主題的相關文章,但它們都給出了日志記錄的例子,再也沒有回來過。這是一把小提琴這包括兩種處理方法init()*使用Promise和使用async/await..無論我嘗試什么,我都無法使用getPostById(id).這個職位的問題是:如何創建一個函數,該函數將返回getPostById(id) ?編輯:許多好的答案試圖解釋什么是承諾的主要執行循環。經過大量的視頻和其他很好的閱讀之后,下面是我現在所理解的:我的職能init()正確返回。但是,在主事件循環中:它返回承諾,那么我的工作就是從有點并行循環(不是一個新的真正線程)。為了捕獲并行循環的結果,有兩種方法:使用.then( value => doSomethingWithMy(value) )使用let value = await myAsyncFn()..現在是愚蠢的打嗝:等待只能在async職能:P因此,它本身就返回了一個承諾,可以用在await應該嵌入到async函數,該函數可用于await等等.。這意味著我們不能真正等待承諾:相反,我們應該無限期地捕獲并行循環:.then()或async/await.謝謝你的幫助!
異步函數不返回值,但是控制臺日志()做:如何做?
LEATH
2019-07-22 10:00:43