在React应用程序中挣扎承诺链 [英] Struggle with chaining of promises in react application

查看:73
本文介绍了在React应用程序中挣扎承诺链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript,React-发送多个同时进行的ajax调用承诺.基本上,我想链接这些呼叫,如果一个服务器呼叫完成,则仅执行下一个呼叫,并收集来自makeServerCalls内的端点/pqr的呼叫的成功响应.

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?

推荐答案

您可以使用 Async 库.无需重新发明轮子.

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

有一个瀑布函数,该函数包含一系列要串行执行的函数.您可以将功能1的结果传递给功能2到功能3,依此类推.一旦完成瀑布执行,您将在回调中获得结果.您可以在文档中了解更多信息.

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.

这篇关于在React应用程序中挣扎承诺链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆