Problems not captured by catch after the second task in promise reject

The

code is as follows: how can I capture the reject? of any previous task in the tail catch


var task1 = new Promise(function(resolve, reject){
  resolve("success");
});
var task2 = new Promise(function(resolve, reject){
  reject("error"); 
});

task1.then(task2)
.catch(function(error) {
    console.log("catched:", error);
});

report VM266:5 Uncaught (in promise) error

Oct.22,2021

task1.then(function () {
        return task2
    })
    .catch(function(error) {
        console.log('catched:', error);
    });

. Then is a function, and task2 is a Promise object, so you must not catch later


because you task2 this promise throws an error but does not have catch function to capture it, if task1 and task2


the promise of reject must follow catch to catch the failure, otherwise it will report an error

var task2 = new Promise(function(resolve, reject){
  reject('error'); 
}).catch(function(error) {
    console.log('catched:', error);
});

this is also possible


add that if your task runs in parallel and has no dependencies, you should use Promise.all

var jobs = [];
var task1 = new Promise(function(resolve, reject){
  resolve('success');
});
var task2 = new Promise(function(resolve, reject){
  reject('error'); 
});

jobs.push(task1);
jobs.push(task2);

Promise.all(jobs).catch(function(error) {
    console.log('catched:', error);
});
Menu