'await & async when you don't care about errors
Let's take a simple example, fs.stat
. I can promisify fs.stat
and write:
const stats = await stat(file, fs.constants.R_OK);
but if the file doesn't exist this throws. Other than wrapping every await in a try/catch, is there a clean pattern or wrapping library that can be used here? Something that perhaps ends up with stats === undefined | null
?
Solution 1:[1]
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));
Solution 2:[2]
How about a simple wrapper:
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(...))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yuval Perelman |
Solution 2 | Paul Grimshaw |