Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making 2 sequential requests with Axios - second request depends on the response of 1st

The following code is not waiting for the else part to return data before resolving.

Where I'm going wrong with this code?

return request.get(`${<URL1>}`)
.then((res) => {
    if (res1.data[0]) {
        data1 = res.data[0]};
    } else {
        request.get(`${<URL2>`)
            .then((res2) => {
                data1 = res2.data
            });
    }
    return Promise.resolve(data1);
})

Thanks in advance.

San

like image 768
kallada Avatar asked Dec 06 '22 13:12

kallada


1 Answers

That is because you're doing it wrong :)

When the program execution encounters an 'async' operation (making a network request with axios), it schedules the task and continues execution of the following lines of code. This include any return statements.

Your return should appear in the 'then' clause:

return request.get(`${<URL1>}`)
    .then((res1) => {
        if (res1.data[0]) {
            data1 = res1.data[0]
            return Promise.resolve(data1);
        } else {
            request.get(`${<URL2>`)
                .then((res2) => {
                    data1 = res2.data
                    return Promise.resolve(data1);
                });
        }
    });

Hope this helps...

Clinton.

like image 160
Clinton Yeboah Avatar answered Dec 10 '22 08:12

Clinton Yeboah