AsyncFunction是否经常异步运行?

时间:2019-02-07 02:36:47

标签: javascript node.js async-await es2017

我正在编写一个模块来获取和运行一些类似koa的中间件。以下代码段演示了其工作原理。

function _createNext(it) {
  return async () => {
    const result = it.next()
    if (!result.done) {
      const middleware = result.value
      const next = _createNext(it)
      await middleware(next)
    }
  }
}

function _createMiddleware(x) {
  return async (next) => {
    console.log(`start: ${x}`)
    await next()
    console.log(`end: ${x}`)
  }
}

const arr = [
  _createMiddleware('a'),
  _createMiddleware('b'),
  _createMiddleware('c'),
]

const arrIterator = arr[Symbol.iterator]()
const next = _createNext(arrIterator)

console.log('1st Line')
next()  // <--- (*)
console.log('2nd Line')

我希望“第二行”应该在“第一行”之后打印,因为我没有在{strong>行(*)上await next() next()应该是异步的。相反,在我看来next()是同步运行的。

// ACTUAL result
1st Line
start: a
start: b
start: c
2nd Line
end: c
end: b
end: a

// EXPECTED result
1st Line
2nd Line
start: a
start: b
start: c
end: c
end: b
end: a

然后我尝试如下更新_createNext函数,一切正常。

function _createNext(it) {
  return () => {
    return Promise.resolve()
      .then(async () => {
        const result = it.next()
        if (!result.done) {
          const middleware = result.value
          const next = _createNext(it)
          await middleware(next)
        }
      })
  }
}

function _createMiddleware(x) {
  return async (next) => {
    console.log(`start: ${x}`)
    await next()
    console.log(`end: ${x}`)
  }
}

const arr = [
  _createMiddleware('a'),
  _createMiddleware('b'),
  _createMiddleware('c'),
]

const arrIterator = arr[Symbol.iterator]()
const next = _createNext(arrIterator)

console.log('1st Line')
next()  // <--- (*)
console.log('2nd Line')

我对第一个代码段的问题感到困惑。我认为AsyncFunction的行为非常像Promise,其中函数内容应始终在nextTick中运行。

有人可以帮忙解释一下吗?非常感谢。

0 个答案:

没有答案