[英]Async/await seemingly not working
我不確定這是怎么回事。 但我有一個功能,這使得利用Axios公司一個簡單的API調用,它的作用是返回由API來的字符串。
async function callSomeApi () {
const res = await axios.get('http://someapi.com')
console.log(res) // here I get the value I expected
return res // this is going to be a simple string
}
事情按預期進行,問題是當我在另一個函數中調用callSomeApi
時。 事情在運轉
async function doSomething () {
const someApiRes = await callSomeApi()
console.log('I will be displayed before someApiRes is finished.')
console.log(`someApiRes will be undefined: ${someApiRes}`)
}
顯然,我對異步/等待有一些誤解,但我不太了解。 如何修復我的代碼?
我弄清楚了,事實證明它與async/await
無關。 好吧,它確實做到了,但是不像我想象的那樣。 我將其留在此處,以防其他人遇到相同的情況並相應地更新OP。
在我的someApiCall
示例代碼中,為簡單起見,我返回了一個字符串。 但實際上,我正在返回一個包含所需字符串的對象。 因此,請考慮如下所示的res
:
{
myString: 'blah'
somethingElse: 'blabla'
}
這很可愛,但是當需要在doSomething
調用中使用它時,我實際上是在這樣做:
async function doSomething () {
const someApiRes = await callSomeApi().myString // here is how it was actually being done
console.log('I will be displayed before someApiRes is finished.')
console.log(`someApiRes will be undefined: ${someApiRes}`)
}
我愚蠢地沒有意識到await
不會運行我的函數,然后訪問myString
屬性,並且我什至沒有想到在編寫我的問題時這可能是一個問題。
因此,解決我的問題的方法如下:
async function doSomething () {
const someApiRes = await callSomeApi()
const myString = someApiRes.myString()
console.log('This is all working as expected.'))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.