我得到一个args数组作为参数,然后我根据下面的算法进行了大量的服务器调用。
迭代args数组,
一个。一次拉3并发送3次调用到端点/ pqr
湾一旦3个电话进入步骤' 2.a'成功发送3个Post调用到endpoint / def
℃。收集步骤' 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); }); }; }
我面临几个问题
答案 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){
});