node.js - 在这种情况下如何使用异步功能降低复杂性?
问题描述
我有一个 Express 应用程序,server.js 代码中的一些功能是这样的:
server.post('/post', (req, res) => {
//some code here...
function a() {
return new Promise(resolve => {
//some code here...
resolve(`result`)
});
};
async function output() {
console.log('Waiting');
const result = await a();
console.log(result);
//some code here...
};
output();
});
它工作得很好,但太嵌套而无法阅读。我想像这样移动function a()
外部server.post
:
function a() {
return new Promise(resolve => {
//some code here...
resolve(`result`)
});
}
server.post('/post', (req, res) => {
//some code here...
a();
async function output() {
console.log('Waiting');
const result = await a();
console.log(result);
//some code here...
};
output();
});
但是这样就不能像以前那样工作了……
在这种情况下如何降低第一个例子的复杂度?
解决方案
您通常可以使用以下模式处理它:
server.post('/post', async (req, res, next) => {
// Some async code here
let stuff = await example();
await a(stuff);
res.send(...);
next();
});
这里的关键是要有一个next
参数,这样你就可以在 Promise 结束时进行链接。这是一个必须调用的回调函数。未能调用它会使您的请求挂起。
推荐阅读
- python - tkinter 模块中按钮的对齐方式
- swift - 在 Swift 4 中创建类似 Spotlight 的窗口?
- python - 如何通过子类从主类访问初始化变量?
- kotlin - 如何访问 RecyclerView 适配器 itemView 项目?
- ibm-watson - 用于测试的成熟 Watson Assistant 集成
- bash - 如何用当前时间命名文件?
- matlab - Matlab:摆脱循环
- c++ - OpenGL试图渲染一个立方体,但平面之间有奇怪的线条
- java - Android studio 3.2.1 未构建新项目和 color.xml 文件
- javascript - Javascript Promise.prototype.then() 排序问题