kroos
kroos

Reputation: 37

How do reduce complexity with async function in this case?

I have an Express app and some function in server.js code is like this:

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();
});

It works good but too nested to read. I want to move the function a() outside the server.post like:

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();
});

But like this cannot work as before...

In this case how to reduce the complexity of the first example?

Upvotes: 1

Views: 337

Answers (1)

tadman
tadman

Reputation: 211560

You can usually handle it with this pattern:

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

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

    res.send(...);

    next();
});

The key here is to have a next argument so you can chain through when the promises wrap up. This is a callback function that must be called. Failing to call it leaves your request hanging.

Upvotes: 1

Related Questions