Promises.all does not hit catch() block when one promise fails?

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?

Answers


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.


Need Your Help

Hosts file missing on Mac OS X - Xcode Failing to compile code

xcode osx file cat hosts

I've tried to run my first objective-c code in Xcode... Compilation process was successfully, however an error returns " invalid host string: 'localhost' ".

how to create a thread to refresh data in 3 second interval

android

I need a thread (it does httppost ,and parse the answer xml and refresh listview to set the changes from parsed xml) in 3 sec interval

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.