異步函數(shù)不返回值,但是控制臺(tái)日志()做:如何做?我有ES6課程init()方法負(fù)責(zé)獲取、轉(zhuǎn)換數(shù)據(jù),然后更新類的屬性this.data新轉(zhuǎn)換的數(shù)據(jù)。到目前一切尚好。這個(gè)類本身有另一個(gè)getPostById()方法,只做聽(tīng)起來(lái)像的事。下面是這個(gè)類的代碼: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 )
}}直截了當(dāng),除了我有一個(gè)async/await機(jī)制init()方法?,F(xiàn)在,此代碼將正確工作:let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')allPosts.init()
.then( d => console.log(allPosts.getPostById(4)) )// resulting Object correctly logged in console但是它只會(huì)被打印到控制臺(tái)上:我如何使用allPosts.getPostById(4)作為return某項(xiàng)功能?比如: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但不是最終價(jià)值。我讀過(guò)幾篇關(guān)于這一主題的相關(guān)文章,但它們都給出了日志記錄的例子,再也沒(méi)有回來(lái)過(guò)。這是一把小提琴這包括兩種處理方法init()*使用Promise和使用async/await..無(wú)論我嘗試什么,我都無(wú)法使用getPostById(id).這個(gè)職位的問(wèn)題是:如何創(chuàng)建一個(gè)函數(shù),該函數(shù)將返回getPostById(id) ?編輯:許多好的答案試圖解釋什么是承諾的主要執(zhí)行循環(huán)。經(jīng)過(guò)大量的視頻和其他很好的閱讀之后,下面是我現(xiàn)在所理解的:我的職能init()正確返回。但是,在主事件循環(huán)中:它返回承諾,那么我的工作就是從有點(diǎn)并行循環(huán)(不是一個(gè)新的真正線程)。為了捕獲并行循環(huán)的結(jié)果,有兩種方法:使用.then( value => doSomethingWithMy(value) )使用let value = await myAsyncFn()..現(xiàn)在是愚蠢的打嗝:等待只能在async職能:P因此,它本身就返回了一個(gè)承諾,可以用在await應(yīng)該嵌入到async函數(shù),該函數(shù)可用于await等等.。這意味著我們不能真正等待承諾:相反,我們應(yīng)該無(wú)限期地捕獲并行循環(huán):.then()或async/await.謝謝你的幫助!
異步函數(shù)不返回值,但是控制臺(tái)日志()做:如何做?
BIG陽(yáng)
2019-07-26 15:14:03