1

I'm trying to run a function when two compilation steps are complete, but the success callback keeps getting called even one fails. Here's the code:

function compile(tplStr) {
  return new Promise(function(resolve,reject) {
    // compile template here
    var tpl = new function(){};
    resolve(tpl);
  });
}

function parse(json) {
  return new Promise(function(resolve,reject) {
    try {
      var obj = JSON.parse(json);
      resolve(obj);
    } catch(err) {
      console.log('JSON parse failed');
      reject(err);
    }
  });
}

var i = 0;

function bothReady() {
  $('#c').text(++i);
}

function oneFailed(err) {
  console.log('oneFailed hit');
  $('#c').text(err.message);
}

var compileProm = compile($('#a').val());
var parseProm = parse($('#b').val());

Promise.all([compileProm,parseProm]).then(bothReady).catch(oneFailed);


$('#a').on('input', function() {
  Promise.all([compile($('#a').val()),parseProm]).then(bothReady).catch(oneFailed);
});


$('#b').on('input', function() {
  Promise.all(compileProm,parse($('#b').val())).then(bothReady).catch(oneFailed);
});

code pen

When I create a syntax error in the JSON portion it logs "JSON parse failed" but does not log "oneFailed hit" like I'd expect. Why not? Shouldn't the .catch block be ran if any of the promises are rejected?

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • [Works for me](http://codepen.io/anon/pen/kDtCa) after I added jQuery and RSVP to the code pen. – Bergi Jun 28 '14 at 19:44
  • 1
    However, your code sometimes does log `oneFailed hit` but *not* `JSON.parse failed` because you didn't update the `compileProm` and `parseProm` variables. – Bergi Jun 28 '14 at 19:45

1 Answers1

3

Your code doesn't work correctly when something is typed inside of #b because instead of passing an iterable to Promise.All 2 parameters are passed instead.

The result is that while both promises run, only the result of the first one is taken into account by the continuation of all.

The code read

Promise.all(compileProm,parse($('#b').val())).then(bothReady).catch(oneFailed);

Instead of

Promise.all([compileProm,parse($('#b').val())]).then(bothReady).catch(oneFailed);

PS: The 2 other calls are correct it explain why the problem seem to happen only when editing the JSON.

Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75