Javascript 异步/等待似乎不起作用

Javascript 异步/等待似乎不起作用,javascript,asynchronous,async-await,Javascript,Asynchronous,Async Await,我不知道这里发生了什么事。但是我有一个函数,它使用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 st

我不知道这里发生了什么事。但是我有一个函数,它使用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/Wait有一些误解,我不太明白。如何修复我的代码?

我发现它与
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.'))
}

await
下面的所有行在
await
解析之前都不会运行,听起来好像一切正常?如果您想让
callSomeApi
控制台.log
s之后而不是之前出现,只需将
await callSomeApi()
移动到它们下面。这就是我的想法,但在这种情况下,它们似乎在
await
解决之前运行,这就是我得到
undefined
的原因。(或者至少这是我对它的解释)@robertotomás如果什么都做不了,异步函数已经自动返回承诺了。-您的代码似乎工作正常(使用虚拟承诺而不是axios.get)-因此,除非
res
不是您所认为的那样,否则问题不在于您使用axios(和
res.statusText
而不是
res