How can I call one error handler with nested promises?

Why deferred.reject()does not one of the calls start the handler .fail()at the end? How can I call one error handler with nested promises? I need nested promises to close.

When I run the reject on d1, it still fully matches the resolution / reject d2. If I add .fail()to the block d1, then it will catch the deviation. But this is what I'm trying to avoid, a handler .fail()for each nested promise.

var Q = require('q');

somePromise().then(function (v1) {

  var d1 = Q.defer();

  asyncFunc1(v2, function (err, v3) {
    if (!v3) 
      d1.reject(new Error('error'));
    else
      d1.resolve(true);

    return d1.promise.then(function (promise1Kept) {
      var d2 = Q.defer();
      asyncFunc2(v4, function (err, v5) {
        if (!v5)
          d2.reject(new Error('error'));
        else
          d2.resolve(true);
      });
      return d2.promise.then(function (promise2Kept) {
        console.log('end of promise chain');
      });
    });
  });
}).fail(function (err) {
  console.log('Error!');
  console.log(err);
});
+4
source share
1 answer

promises . , , .

var Q = require('q');
var func1 = Q.denodeify(asyncFunc1);
var func2 = Q.denodeify(asyncFunc2);

somePromise().then(function (v1) {
  return func1(v2);
}).then(function (v3) {
  if (!v3) throw new Error("error");

  return func2(v4);
}).then(function (v5) {
  if (!v5) throw new Error("error");

  console.log("end of promise chain");
}).fail(function (err) {
  console.log('Error!');
  console.log(err);
});
+1

All Articles