Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - 非异步函数内部的异步函数与异步函数?(async function vs async function inside non async function?)

function scaryClown() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('a')
    }, 1000)
  });
}

function msg2() {
  const msg2 = async () => {
    const result = await scaryClown()
    console.log(result)
  }

  msg2()
}

async function msg() {
  const result = await scaryClown()
  console.log(result)
}

What is the difference between the two functions msg and msg2?

(msg和msg2这两个函数有什么区别?)

  ask by Henok Tesfaye translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

msg returns a promise, msg2 (the outer one) doesn't.

(msg返回一个承诺, msg2 (外部)不返回。)

That means it's possible for code calling msg to know when the asynchronous operation completes, but it's not possible for code calling msg2 .

(这意味着调用msg代码有可能知道异步操作何时完成,但是调用msg2代码则msg2 。)

( msg2 also fails to handle rejection or pass the chain to the caller so the caller can handle rejection, which breaks one of the fundamental rules of promises: always either handle rejection or return the chain.)

(msg2也无法处理拒绝或将链传递给调用方,因此调用方可以处理拒绝,这违反了promise的基本规则之一:始终处理拒绝或返回链。))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...