简体   繁体   中英

Promise.all error handling — make result of one Promise accessible in another Promise's catch?

I'm writing a simple build script which compiles some files. The only problem remaining is the error handling. It works, but I want add additional content to the error messages. Here is a snippet of the code in question:

const promises = []

for (let file of files) {
  promises.push(Promise.all([exec(compile(file)), Promise.resolve(file)]))
}

Promise.all(promises.map(p => p.catch(e => console.log(e))))
.then(result => {
  /* result is now an array with the following pattern:
     [[stdout, filename], [stdout, filename], ...]
   */
});

The exec function returns some stdout containing data which does not state which file was used. Therefore I have added a Promise.all containing both the exec function and a promise which immediately resolve and return the filename. I need the data returned from exec and the filename for when I need to write the files to the system. Because I still want the last then to run regardless of any errors, I handle the errors for each file individually (hence the .map ). The only issue is that the stdout from exec does not reference the file it used. So the error messages get confusing. I would something like the following:

p.catch(e => console.log(`error happened in ${file}:`, e))

I'm not sure how I can access the file variable from within the catch . Any ideas?

You should directly add the catch when calling the function:

  for (let file of files) {
    promises.push(
       exec(compile(file))
         .then(result => [result, file])
         .catch(error => [error, file])
    );
  }

  Promise.all(promises).then(results => {
    //...
  });

You might want to put the catch in the loop where the respective file is still in scope:

Promise.all(files.map(file => 
  Promise.all([
    exec(compile(file)).catch(e => console.log(`error happened in ${file}:`, e)),
    file
  ])
)).then(result => {
  /* result is now an array with the following pattern:
     [[stdout/undefined, filename], [stdout/undefined, filename], ...]
   */
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM