为什么 return 仍然在多个 await 语句之前执行?

Why does return still execute before multiple await statements?

根据我的理解,await 使整个函数等待,直到它前面的语句完成,对吗?我不确定为什么下面的代码打印这个:

RES: [object Promise]
cn: 你好wurld!
mg: வணக்கம் wurld!
xh: Molo wurld!
FINAL: Url hello!

这是我的代码:

const rp = require('request-promise')
const apiKey = //commented out for obvious reasons lol

const muddle = async(toTranslate)=>{
  let options = {
    method: 'GET',
    json: true,
    uri: `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${apiKey}&text=${toTranslate}&lang=en-zh`
  }
  let response = await rp(options)
  let newText = response.text[0]
  console.log('cn: ' + newText)

  options.uri =`https://translate.yandex.net/api/v1.5/tr.json/translate?key=${apiKey}&text=${toTranslate}&lang=zh-ta`
  response = await rp(options)
  newText = response.text[0]
  console.log('mg: ' +newText)

  options.uri =`https://translate.yandex.net/api/v1.5/tr.json/translate?key=${apiKey}&text=${toTranslate}&lang=ta-xh`
  response = await rp(options)
  newText = response.text[0]
  console.log('xh: ' +newText)

  options.uri = `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${apiKey}&text=${newText}&lang=xh-en`
  response = await rp(options)
  newText = response.text[0]
  console.log('FINAL: ' + newText)

  return response.text[0] //why does this fire before all the lines that include await before it?
}


let toLog = muddle('Hello wurld!')
console.log('RES: '+ toLog)

RES: [object Promise] 不应该是最后打印的行吗?抱歉,代码量很大,但大部分都是多余的。每个块只是对翻译 API 的请求,翻译 return 从它前面的请求中翻译。我误解了 await 的工作原理吗?我想 return 经过四次翻译 运行 的最终字符串 ('Url hello!)

最后没有打印 RES 是正常的,因为您不会在记录之前等待 muddle 函数完成。

你有两种选择来解决这个问题:

使用 then 语法:

muddle('Hello wurld!').then(toLog => {
  console.log('RES: '+ toLog)
})

将您的调用包装在另一个异步函数中:

async function main() {
  const toLog = await muddle('Hello wurld!')
  console.log('RES: '+ toLog)
}
main();

不过要小心第二个:您最终可能会得到同步代码。更容易处理但可能效率低下