Skip to content
Advertisement

Struggle with chaining of promises in react application

JavaScript, React – sending multiple simultaneous ajax calls struggling with promises. Basically I want to chain the calls, if one server call completes then only do next call, and collect the successful response of calls from endpoint /pqr made inside makeServerCalls.

import Promise from 'bluebird';
import request from 'superagent';

// sends a post request to server 
const servercall2 = (args, response) => {
    const promise = new Promise((resolve, reject) => {

        const req = request
            .post(`${baseUrl}/def`)
            .send(args, response)
            .setAuthHeaders();

        req.endAsync()
            .then((res) => resolve(res))
            .catch((err) => reject(err));
    });

    return promise;
};

// sends a post request to server
const servercall1 = (args) => {
    const promise = new Promise((resolve, reject) => {

        const req = request
            .post(`${baseUrl}/abc`)
            .send(args)
            .setAuthHeaders();

        req.endAsync()
            .then((res) => resolve({res}))
            .catch((err) => reject(err));
    });

    return promise;
};


// function to send request to cgi server to execute actions from ui
async function makeServerCalls(args, length) {

    // convert args to two dimensional array, chunks of given length [[1,2,3], [4,5,6,], [7,8]]

    const batchedArgs = args.reduce((rows, key, index) => (index % length === 0 ? rows.push([key])
        : rows[rows.length - 1].push(key)) && rows, []);

    const responses = [];

    for (const batchArgs of batchedArgs) {
        responses.push(
            // wait for a chunk to complete, before firing the next chunk of calls
            await Promise.all(

                ***// Error, expected to return a value in arrow function???***
                batchArgs.map((args) => {
                    const req = request
                        .get(`${baseUrl}/pqr`)
                        .query(args)

                    // I want to collect response from above req at the end of all calls.
                    req.endAsync()
                        .then((response) =>servercall2(args,response))
                        .then((res) => res);
                })
            )
        );
    }

    // wait for all calls to finish
    return Promise.all(responses);
}

export function execute(args) {
    return (dispatch) => {

       servercall1(args)
           .then(makeServerCalls(args, 3))
           .then((responses) => {
                    const serverresponses = [].concat(...responses);
                    console.log(serverresponses);
            });
    };
}

Error: expected to return a value in arrow function. What am I doing wrong here?

Is this a right chaining or it can be optimized?

What happens if some call fails in between?

Answer

You can use Async library for this. No need to re-invent the wheel.

There is a waterfall function that takes a list of functions that execute in series. You can pass result of function 1 to function 2 to function 3 and so on. Once complete waterfall executes, you get the result in callback. You can read more about it in the docs in the link above.

Advertisement