Why did we use a .catch() rather than a catch() block while handling errors

Hello guys, can someone explain why in the following code, we use a .catch outside the function body that is when the function run is being called. Why don't we use a catch block directly after the try ? If we don't use a catch block inside, then what's the need of the try, we can remove it ? From what I have understand, this is why we might want to use a .catch() outside the function body rather than inside: we don't want the flow inside the function to stop every time there is an error with our return promises, instead of handling each error 1 at a time, let's just handle it at an upper level, that is when we call the function
async function run(username,password) {
try {
const database = client.db('socialMedia');
const users = database.collection('users');
const doc = {user : `${username}`, pwd : `${password}`};

const result = await users.insertOne(doc);
console.log(result);
}
finally {
await client.close();
}
}

run('username','secret')
.catch(console.dir);
async function run(username,password) {
try {
const database = client.db('socialMedia');
const users = database.collection('users');
const doc = {user : `${username}`, pwd : `${password}`};

const result = await users.insertOne(doc);
console.log(result);
}
finally {
await client.close();
}
}

run('username','secret')
.catch(console.dir);
2 Replies
Chief
Chief4w ago
You pretty much got it right If you want to handle errors locally inside the function, then it makes sense to add the catch block with the try. However, if you need some robust way of handling any errors, you are propagating the error outside. This is because the function is async it is always going to return a promise. The reason why you dont handle the Exception inside the method is because you want the error to be handled outside, that is why the .catch is written with function run I hope you get what I am trying to say
Faker
FakerOP4w ago
yeah I see ty !
Want results from more Discord servers?
Add your server