0

I want to add chaining to http.request(url).post(uri) from chai npm module for mocha test feramework. so I need to add field and attach promises that is for post as long as the values from an array that will pass as parameters for these chai methods as follow:

var props = ['name:Sara', 'email:sara@mail.com', 'password:pass'];
var route = '/app/login';
    chaiHttp.request(url).post(route)
    ./* add field promises as much as the array length */
    .then(function(res){
      // do something with this res
    });

I do something like this already:

var props = ['name:Sara', 'email:sara@mail.com', 'password:pass'];
var route = '/app/login';
chaiHttp.request(url).post(route).field('name','Sara').field('email','sara@mail.com').then(function(res){
  //do something with response
  });
SAlidadi
  • 85
  • 10
  • Have you tried a loop? Or `props.reduce`? – Bergi Jul 27 '16 at 14:06
  • Yes I tried it also some solutions from here http://stackoverflow.com/questions/17757654/how-to-chain-a-variable-number-of-promises-in-q-in-order – SAlidadi Jul 27 '16 at 15:25
  • And it didn't work? Why? Please [edit] your question to include these attempts so we can direct you. – Bergi Jul 27 '16 at 15:32

1 Answers1

0

The promise returned by post() should be the receiver of the then() call, but I think you're worried that the intervening field() calls will do some harm.

But the hard-coded version you have proves that the field calls propagate their receiver so they can be chained. Therefore, it's perfectly okay to do something like this:

var postPromise = chaiHttp.request(url).post(route);  // this won't start until your code returns from the event loop
['name:Sara', 'email:sara@mail.com', 'password:pass'].forEach(function(pair) {
    var components = pair.split(':');
    postPromise.field(components[0], components[1]);
});
postPromise.then(function(res) {
});
danh
  • 62,181
  • 10
  • 95
  • 136