0

The problem is related to promises. I just started learning Express, and using to make HTTP requests.

The app relies heavily on making external requests to function, so for this reason, I am ending up with a very ugly app that is primarily a nested mess.

Example of a scenario (dummy code):

app.get('/v1/example', async function(req, res) {
    let bearer = null;
    try {bearer = req.header('authorization').split(' ')[1];}
    catch (e) {bearer = params.token;}
    checkUser(bearer).then(r => {
        res.json(r.data);

    res.json(r.data);
        action1(bearer).then(r => {
            action2(bearer).then(r => {
                res.json(r.data);
            }).catch(e => {
                try {
                    res.status(e.response.status);
                    res.send(e.response.data);
                }
                catch (e) {console.log('oops')}
            })
        }).catch(e => {
            try {
                res.status(e.response.status);
                res.send(e.response.data);
            }
            catch (e) {console.log('oops')}
        })

    }).catch(e => {
        try {
            res.status(e.response.status);
            res.send(e.response.data);
        }
        catch (e) {console.log('oops')}
    })
})

Is there a better way to do that? Knowing that in a more elegant fashion? How can I properly wait for the above previous promise to complete before firing up the function below?

Is there anything that you can suggest?

Right now, I did a very dirty trick, and of course, this doesn't scale: I am setting up an interval that checks if the variable that I need is defined or not, and when the variable is finally defined, it exits the interval and timeout.


            const intervalObj = setInterval(function() {
                let MIME = helpers.getMIME(image_response.extension)
                const file = image_response.image_path;
                const fileExists = fs.existsSync(file);

                if (fileExists) {
                    clearInterval(intervalObj);
                   // do the next task.

                }
            }, timeout);

Thank you.

user3822343
  • 13
  • 1
  • 5
  • You must call `res.json()` exactly once, not three times – Bergi Oct 03 '22 at 21:44
  • 1
    You should consider [using `async`/`await` instead of `then()` chaining (or worse, nesting)](https://stackoverflow.com/a/44664037/1048572) – Bergi Oct 03 '22 at 21:50

0 Answers0