异步箭头函数返回类型

我正在尝试使用异步箭头函数作为另一个函数的回调。在这里,从箭头函数返回的值没有任何意义,因此我什么也不返回。但是,由于我将其用作异步函数,所以我需要从箭头函数返回一个值或Promise.resolve(“ somevalue”)。

当我测试下面的代码而不返回任何值时,它起作用了,但是我不确定它是否正确。

const ack = async (result) => {
  await this.service.updateObject(result);
} // No return is given

方法ack称为另一个函数的回调。

评论
陌路夜未央
陌路夜未央

No, what you're doing currently is just fine. async functions automatically return Promises which resolve to whatever is returned from the function. If nothing is returned explicitly, then the Promise resolves to undefined, just like calling a function that doesn't return anything results in undefined being returned.

So if you just need the function to do something, but you don't need a possible result to be used by the consumer of the function, feel free to use await inside the function without returning anything. This is a common pattern.

点赞
评论