如何做一个有条件的https请求?

时间:2018-10-08 00:44:55

标签: node.js

这基本上就是我想要做的:

var sendRequest= false;  //may be true

https.request(request_params, function(response){  //only sends a request if sendRequest == true
    //do something with response if request has been sent      
    someObjWithCallback.itsfunction(its_params, function(resp){
          //do something with response
    }        
}

如何确保仅在sendRequest条件为true时运行https.request。

注意:someObjWithCallback.itsfunction(..)必须在两种情况下运行(sendRequest为true或false)。因此,回调函数必须在任何情况下都运行。

1 个答案:

答案 0 :(得分:0)

您可以使用if语句检查变量:

if (sendRequest) {
  https.request(request_params, function(response){  //only sends a request if sendRequest == true
    //do something with response if request has been sent      
    someObjWithCallback.itsfunction(its_params, function(resp){
          //do something with response
    }        
  })
}

或利用&&运算符(并阅读this excellent article

sendRequest && https.request(request_params, function(response){  //only sends a request if sendRequest == true
    //do something with response if request has been sent      
    someObjWithCallback.itsfunction(its_params, function(resp){
          //do something with response
    })     
}

或弄乱三元表达式(但前提是您想在请求为false时对请求执行代替的操作)

sendRequest ? https.request(request_params, function(response){  //only sends a request if sendRequest == true
    //do something with response if request has been sent      
    someObjWithCallback.itsfunction(its_params, function(resp){
          //do something with response
    }        
}) : console.log('lol, don't actually do this if you dont have an "else" condition...')