等待最后一条指令有用吗

Ron*_*ere 8 javascript function promise async-await ecmascript-6

我看到了下面的代码,想知道除了强制该方法具有关键字之外async,在最后一条指令上指定等待是否有用?例子

async example(){
  //... whatever code

  //Last instruction
  await functionReturningAPromise()
}
Run Code Online (Sandbox Code Playgroud)

请注意,在这里我怀疑退货丢失了,但即使有退货,我的问题仍然存在。

async example(){
  //... whatever code

  //Last instruction
  return await functionReturningAPromise() //Is this useful ? or should we return directly
}
Run Code Online (Sandbox Code Playgroud)

我个人认为没有真正的兴趣。

Ron*_*ere 3

所以这是我尝试仅用代码来回答我自己的问题。我的结论是

return await1)我不同意在 try/catch 块之外多余的语句。它将改变example()if 调用的返回值await

2)将 放在await最后一条语句上将保证如果我在解决之后调用任何内容,则将在解决await example()完成(正如@Kristianmitk所指出的)。 functionReturningAPromise()

3)使用 调用异步函数不起作用,await好像Promise.all在其中启动了多个承诺(并且await在内部未添加 -ed )一样。

查看测试结果 3/4/5 我得到结果得到慢速异步函数的日志。

function asyncSlow(testName){
  return new Promise(resolve => {
      setTimeout(() => {
        console.log('slow is done from' + testName)
        resolve('slow-' + testName);
      }, 300);
    });
}

function asyncFast(testName){
  return new Promise(resolve => {
      setTimeout(() => {
        console.log('fast is done from' + testName)
        resolve('fast-' + testName);
      }, 100);
    });
}

async function test1(){
  await asyncSlow('test1')
  await asyncFast('test1')
}

async function test2(){
  await asyncSlow('test2')
  return await asyncFast('test2')
}

async function test3(){
  asyncSlow('test3')
  return await asyncFast('test3')
}

async function test4(){
  asyncSlow('test4')
  return asyncFast('test4')
}

async function test5(){
  asyncSlow('test5')
  asyncFast('test5')
}

async function main(){
  const res = await test1()
  console.log('res = ' + res)
  
  const res2 = await test2()
  console.log('res2 = ' + res2)
  
  const res3 = await test3()
  console.log('res3 = ' + res3)
  
  const res4 = await test4()
  console.log('res4 = ' + res4)
  
  const res5 = await test5()
  console.log('res5 = ' + res5)
}

main()
Run Code Online (Sandbox Code Playgroud)

输出如下:

slow is done fromtest1
fast is done fromtest1
res = undefined
slow is done fromtest2
fast is done fromtest2
res2 = fast-test2
fast is done fromtest3
res3 = fast-test3
fast is done fromtest4
res4 = fast-test4
res5 = undefined
slow is done fromtest3
fast is done fromtest5
slow is done fromtest4
slow is done fromtest5
Run Code Online (Sandbox Code Playgroud)