[英]Conditional Promise Chaining
我得到一個args數組作為參數,然后根據下面的算法進行許多服務器調用。
遍歷args數組,
一種。 一次拉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); }); }; }
我面臨幾個問題
可能就是這樣batchArgs.map
每個項目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);
})
您的文本是一堵磚牆,因此很難理解您實際上要實現的目標,但是我將在給出的代碼中投入2美分。
//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){
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.