异步函数作为回调函数

时间:2017-07-18 19:44:35

标签: javascript

我刚刚开始使用async / await,并且对它如何与回调交互感到困惑。例如,

fooMethod(function() {
    return Promise.resolve("foo");
});

vs

fooMethod(async function() { //add async keyword
    return "foo";
});

必须以特定方式编写fooMethod才能将async函数作为回调处理吗?

如果fooMethod是公共图书馆,我怎么知道向该函数添加async关键字是否安全?

关注

Express router,

app.get('/foo', function (req, res) {
  return res.send("foo");
});



app.get('/foo', async function (req, res) {
  return res.send("foo");
});

这两个功能都有效,但是使用它是否安全?

2 个答案:

答案 0 :(得分:2)

你的两个回调是等价的。 async function只是常规function的语法糖,返回Promise。这意味着您可以像常规函数一样调用async function。这是一个演示:



const foo = async function (arg) {
  return arg * 2
}
const bar = function (arg) {
  return Promise.resolve().then(() => {
    return arg * 2
  })
}

const fooReturn = foo(2)
const barReturn = bar(2)
console.log('foo(2) =>', fooReturn.toString())
console.log('bar(2) =>', barReturn.toString())

fooReturn.then(fooResult => console.log('await foo(2) =>', fooResult))
barReturn.then(barResult => console.log('await bar(2) =>', barResult))




但是,如果采用回调的代码想要获得响应,则除非代码专门用于检查回调函数的返回值并await,否则您将无法使用异步函数。如果它是Promise

答案 1 :(得分:0)

您的两个函数是等效的,但下面演示了如何在await中使用async function每次延迟执行函数执行额外的滴答:



function syncTest() {
  console.log('sync completed')
  return Promise.resolve('foo')
}

async function asyncTest() {
  console.log('async completed')
  return 'foo'
}

async function awaitTest() {
  console.log('await started')
  await void 0
  console.log('await awaited')
  await void 0
  console.log('await completed')
  return 'foo'
}

console.log('start')

syncTest().then(value => console.log(`sync resolved: ${value}`))
asyncTest().then(value => console.log(`async resolved: ${value}`))
awaitTest().then(value => console.log(`await resolved: ${value}`))

Promise.resolve()
  .then(() => console.log('tick 2 completed'))
  .then(() => console.log('tick 3 completed'))
  .then(() => console.log('tick 4 completed'))

console.log('tick 1 completed')