以旁路顺序执行HTTP请求

时间:2018-10-13 12:37:14

标签: javascript node.js json http request

我想要实现的是同步执行HTTP请求的有序序列,但是根据某些变量的值,我希望其中一些变量被绕过。

作为一个例子(我正在使用Javascript中的request库这样做):

request(httpReq1, function(error, response, body) {
  // do something, like handling errors...
  request(httpReq2, function(error, response, body) {
    // do something else
  });
});

因此,这确保了httpReq2将在httpReq1之后执行。

例如,如果某些标志设置为false,我不确定是如何绕过第一个请求,而不是执行httpReq1并等待响应,而是跳到{{ 1}},保持订单

httpReq2

什么是解决此问题的好方法?

3 个答案:

答案 0 :(得分:2)

排序数组中所需的请求列表,然后使用async/await

顺序执行
let requests = [];
if (doRequest1)
  requests.push(httpReq1);

if (doRequest2)
  requests.push(httpReq2);

/* etc .. for httpReq3 and so on */

// now execute them one by one in sequence
for(let req of requests) {
   try {
     await request(req);
   } catch (err) {
     // error handling here
   }
}

答案 1 :(得分:1)

您可以使用async-await来实现。

async apiCall(){ 
    try{
     if(condition){
      const result1 = await request(httpReq1);
     }
     const result2 = await request(httpReq2);
    }
    catch(error){

    }
}

确保请求模块重新运行Promise。否则,创建一个承诺包装。 axios是一个基于Promise的库。

您必须在包含等待功能的函数之前放置异步

答案 2 :(得分:1)

为什么不使用2个条件?

if (dontMakeHttpReq1) {
  request(req1, function(error, response, body) {
    yourRequestProcessing2();
  });
}
else {
  request(req1, function(error, response, body) {
    request(req2, function(error, response, body) {
      yourRequestProcessing2();
    });
    yourRequestProcessing1();
  });
}

编辑:也许您想将请求调用存储在数组中

//Whether request n should skip
var flags = [
  false,
  true,
  false
];
var requests = [
  function(error, response, body) {
    //Process your request 1
  },
  function(error, response, body) {
    //Process your request 2
  },
  function(error, response, body) {
    //Process request 3
  }
];
for (i = 0; i < requests.length; i++) {
  if (flags[i]) {
    request(req1, requests[i + 1]);
  }
  else {
    request(req2, request[i]);
  }
}
相关问题