Two*_*ois 1 javascript asynchronous node.js typescript
我只是在想我们需要使用await 运算符,以及以下两种情况有什么区别。
一
public async updateOne(Model, doc, errorMsg?){
return await Model.findOneAndUpdate({'_id': doc._id}, {'$set': doc}, {upsert:true, new: true}).lean().exec();
}
Run Code Online (Sandbox Code Playgroud)
二
public updateOne(Model, doc, errorMsg?){
return Model.findOneAndUpdate({'_id': doc._id}, {'$set': doc}, {upsert:true, new: true}).lean().exec();
}
Run Code Online (Sandbox Code Playgroud)
我认为结果没有什么区别,但我认为完全没有必要使用 async wait,因为会返回一个 Promise,而我们只需要在 async 函数内调用 updateOne 函数时使用 await 运算符。
正如Oyverus 回答的那样,结果没有区别,但使用async函数会创建另一个 Promise,我为每种情况添加了一些粗略的示例。
在 Promise 代码中使用async updateOne(){ return await Model.findOneAndUpdate(...) }结果,如下所示:
return new Promise((resolve, reject) => {
Model.findOneAndUpdate(...).then(resolve, reject)
})
Run Code Online (Sandbox Code Playgroud)
那么async updateOne(){ return Model.findOneAndUpdate(...) }就是:
return new Promise(resolve => resolve(Model.findOneAndUpdate(...))
Run Code Online (Sandbox Code Playgroud)
一个平原updateOne(){ return Model.findOneAndUpdate(...) }是:
return Model.findOneAndUpdate(...)
Run Code Online (Sandbox Code Playgroud)
我倾向于在可能的情况下使用简单的返回,但/*async*/出于文档目的在代码中保留一个。
/*async*/ write(){
return this.db.write()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3309 次 |
| 最近记录: |