Dino Geek, try to help you

How to handle errors with Promises?


Promises in JavaScript are used to handle asynchronous operations, they let you handle asynchronous errors using approaches that are very similar to synchronous `try/catch`.

There are mainly two ways to handle errors with Promises.

1. Using .catch() block: A Promise object runs the success or failure handlers, even when there’s a JavaScript error in them. If an error is thrown inside the .then() or .catch() handlers, it’s converted into a rejected Promise.

```
let promise = new Promise((resolve, reject) => { throw new Error(“error”);
});

promise.catch(err => console.log(err)); // Error: error
```

The .catch() handler is used to catch all asynchronous and synchronous errors.

1. Using .then() with two parameters: You can provide the second argument to .then function to catch errors.

```
let promise = new Promise((resolve, reject) => { throw new Error(“error”);
});

promise.then(null, err => console.log(err)); // Error: error
```

If promise is resolved then the first function inside the .then() is executed and if promise is rejected then the second function inside the .then() is executed.

Remember, if we use .catch() after a .then(), and the .then() throws an error or returns a rejected Promise, the .catch() will catch that error.

Remember to always have a catch at the end of your promise chain to catch any errors that may have occurred in the previous .then statements because unhandled promise rejections will be deprecated in the future.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use