有条件的承诺链

时间:2017-09-17 04:10:18

标签: javascript ajax reactjs promise axios

我得到一个args数组作为参数,然后我根据下面的算法进行了大量的服务器调用。

  1. 将args数组作为数据发布到endpoint / abc。
  2. 迭代args数组,

    一个。一次拉3并发送3次调用到端点/ pqr

    湾一旦3个电话进入步骤' 2.a'成功发送3个Post调用到endpoint / def

    ℃。收集步骤' 2.a'服务器调用并将其推入数组。

    d。重复步骤a,b,c直到args长度。

  3. 下面给出了整个过程的代码片段,执行从函数execute(args)开始。

    import Promise from 'bluebird';
    
    import request from 'superagent';
    
    // sends a post request to server 
    const servercall2 = (args, response) => {
    
            const req = request
                .post(`${baseUrl}/def`)
                .send(args, response)
                .setAuthHeaders();
    
            return req.endAsync();
    };
    
    // sends a post request to server
    const servercall1 = (args) => {
    
            const req = request
                .post(`${baseUrl}/abc`)
                .send(args)
                .setAuthHeaders();
    
            return req.endAsync()
                .then((res) => resolve({res}))
                .catch((err) => reject(err));
    };
    
    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.
                        return req.endAsync()
                            .then((response) =>servercall2(args,response)); 
                    })
                )
            );
        }
    
        // 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);
                });
        };
    }
    

    我面临几个问题

    1. 2.c似乎没有正常工作"收集步骤' 2.a'服务器调用并将其推入数组。"。错误:希望在箭头函数中返回一个值。我在这做错了什么?请注意,最后我只关心步骤2.a的响应。
    2. 这是一个正确的链接还是可以根据上述要求进行优化?
    3. 我必须做其他任何失败处理吗?

2 个答案:

答案 0 :(得分:1)

可能是这样 - batchArgs.map中的每个项目都应该是Promise我认为?然后Promise.all将等待每个完成:

batchArgs.map((args) => {
    const req = request
        .get(`${baseUrl}/pqr`)
        .query(args)


    // Return promise here
    return req.endAsync()
        .then((response) =>servercall2(args,response))
        .then((res) => res);
})

答案 1 :(得分:1)

你有一段文字砖,所以它有点难以破译你实际想要实现的目标,但我会给出我给出的代码两分钱。

 //Both server calls can be simplified.. no need to
 //wrap in another promise if one is being returned
 const servercall2 = (args, response) => {
       const req = request
            .post(`${baseUrl}/def`)
            .send(args, response)
            .setAuthHeaders();

        return req.endAsync();
};

    //Here... you return no value in the function passed to map, thus an 
    //error is being thrown. You need to return a Promise from here so that
    //it can be passed into Promise.all

        const allFinished = await Promise.all(
        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.
            return req.endAsync()
        })
       );
       allFinished.then(function(results){

       });