首页 > 解决方案 > 在这种情况下如何使用异步功能降低复杂性?

问题描述

我有一个 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();
});

但是这样就不能像以前那样工作了……

在这种情况下如何降低第一个例子的复杂度?

标签: node.jsexpress

解决方案


您通常可以使用以下模式处理它:

server.post('/post', async (req, res, next) => {
    // Some async code here

    let stuff = await example();
    await a(stuff);

    res.send(...);

    next();
});

这里的关键是要有一个next参数,这样你就可以在 Promise 结束时进行链接。这是一个必须调用的回调函数。未能调用它会使您的请求挂起。


推荐阅读