【发布时间】:2018-02-25 21:14:19
【问题描述】:
我得到一个 args 数组作为参数,然后根据下面的算法进行大量服务器调用。
-
使用 args 数组作为数据发布到端点 /abc。
-
遍历 args 数组,
一个。一次拉 3 个,然后向端点 /pqr 发送 3 个 Get 调用
b.一旦步骤“2.a”中的 3 个调用成功,将 3 个 Post 调用发送到端点 /def
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); }); }; }
我面临几个问题
- 2.c 似乎无法正常工作“从步骤 '2.a' 服务器调用收集响应并将其推送到数组中。”。错误:期望在箭头函数中返回一个值。我在这里做错了什么?请注意,最后我只关心步骤 2.a 的响应。
- 这是正确的链接还是可以根据上述要求进行优化?
- 我还需要处理其他故障吗?
【问题讨论】:
标签: javascript ajax reactjs promise axios