Wait and asynchronously when you don't care about errors

Let's take a simple example fs.stat. I can promise fs.statand write:

const stats = await stat(file, fs.constants.R_OK);

but if the file does not exist, it calls. Besides wrapping every expectation in try / catch, is there a clean model or wrapper library that you can use here? Something that maybe ends stats === undefined | null?

+4
source share
2 answers

maybe something like this?

function caughtAwait(func){
  try{
    return await func();
  }
  catch(e){
    console.log(e);
    return null;
  }
}
const stats = caughtAwait(()=>stat(file, fs.constants.R_OK));
+3
source

How about a simple shell:

async function leniently(promise) {
     try {
        return await promise
     } catch(err) {
        return null
     }
}

Used for any promise:

const result = await leniently(stat(file, fs.constants.R_OK))

Or Promise.all(...):

const result = await leniently(Promise.all(...))
0
source

Source: https://habr.com/ru/post/1681260/


All Articles