Mis*_*Guy 8 javascript node.js promise async-await
我正在寻找关于在nodeJS应用程序中使用什么的答案.
我有代码处理我对mssql的通用dB访问.这段代码是使用async函数编写的,然后我使用了一个承诺调用该函数,一切正常.
随着我的应用程序越来越大,代码越来越大,我计划将一些逻辑转移到函数中然后调用它们.
所以我的问题是:使用async/await和promises的组合是否有缺点,或者它真的无关紧要?
Async/await使编写更易读的代码变得更容易,因为在返回内容之前我必须读取和写入多个db,我需要其中一些结果.
所以问题是什么是更好的方法?异步/等待在dB层上设置并且无法更改逻辑层async/await将允许我在函数调用上执行异步/等待,或者如果我继承逻辑,那么我在函数调用中遇到了承诺.
因此,除了能够编写更清晰的代码之外,如果一个人比另一个人有更多的优势,我希望有人可以给我更多的见解.
luc*_*aro 10
async/await与承诺密切相关.async函数返回promises,等待是等待承诺解析的语法糖.
混合使用promises和async函数的唯一缺点可能是代码的可读性和可维护性,但是你当然可以使用async函数的返回值作为promises以及await返回promise的常规函数.
你选择一个与另一个主要取决于可用性(你的node.js /浏览器是否支持async?)和你的审美偏好,但一个好的经验法则可能是:
async/await:return asyncFunction()
.then(result => f1(result))
.then(result2 => f2(result2));
Run Code Online (Sandbox Code Playgroud)
VS
const result = await asyncFunction();
const result2 = await f1(result);
return await f2(result2);
Run Code Online (Sandbox Code Playgroud)
async/await:return asyncFunction()
.then(result => {
return f1(result)
.then(result2 => f2(result, result2);
})
Run Code Online (Sandbox Code Playgroud)
VS
const result = await asyncFunction();
const result2 = await f1(result);
return await f2(result, result2);
Run Code Online (Sandbox Code Playgroud)
return Promise.all(arrayOfIDs.map(id => asyncFn(id)))
Run Code Online (Sandbox Code Playgroud)
小智 6
实际上这取决于您的节点版本,但是如果您可以使用,async/await那么您的代码将更具可读性且更易于维护。当您将函数定义为 'async' 时,它返回一个 native Promise,当您使用 await 调用它时,它会执行 Promise.then。
注意:将您的 await 调用放在 a 中try/catch,因为如果 Promise 失败'catch',您可以在 catch 块中处理它。
try{
let res1 = await your-async-function(parameters);
let res2 = await your-promise-function(parameters);
await your-async-or-promise-function(parameters);
}
catch(ex){
// your error handler goes here
// error is caused by any of your called functions which fails its promise
// this methods breaks your call chain
}
Run Code Online (Sandbox Code Playgroud)
你也可以像这样处理你的“捕获”:
let result = await your-asyncFunction(parameters).catch((error)=>{//your error handler goes here});
Run Code Online (Sandbox Code Playgroud)
提到的这个方法不会产生异常,所以继续执行。
async/await除了本机 Promise 模块实现之外,我认为没有任何性能差异。
我建议使用bluebird模块而不是内置于 node.js 中的本机承诺。
在这一点上,使用 Promises 的唯一原因是调用多个异步作业,Promise.all()否则你通常最好使用 async/await 或 Observables。
| 归档时间: |
|
| 查看次数: |
2603 次 |
| 最近记录: |