javascript - 条件 Promise 链

标签 javascript ajax reactjs promise axios

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

  1. 使用 args 数组作为数据发布到端点/abc。

  2. 迭代 args 数组,

    a.一次拉取 3 个并向端点/pqr 发送 3 个 Get 调用

    b.一旦步骤“2.a”中的 3 个调用成功,就会向端点/def 发送 3 个 Post 调用

    c.从步骤“2.a”服务器调用收集响应并将其推送到数组中。

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

下面给出了整个过程的代码片段,从函数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. 我还需要进行其他故障处理吗?

最佳答案

你有一堵文字墙,所以它变得有点难以破译你真正想要实现的目标,但我会在给出的代码上给出我的两分钱。

 //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){

       });

关于javascript - 条件 Promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260559/

相关文章:

javascript - 如何向表格添加列排序功能?

reactjs - 运行时出现以下错误 "npm start"

reactjs - 使用 Axios 获取 Json 并迭代 ReactStrap Table 中的数据

javascript - 删除 for 循环顶行的所有语句

javascript - Jquery 将一个对象值数组追加到右边的 div

javascript - 在 iframe 中形成 POST 而不影响历史

javascript - $_POST 没有返回值

javascript - JSON 和 AJAX 与 jQuery 有什么区别?

javascript - Promise.all() 返回意外值

javascript - function foo({ defaultValue = {} } = {}) 中的语法是什么意思?