📜 ⬆️ ⬇️

Javascript We work with exceptions and data in async / await constructs without try-catch blocks

New async async / await constructs that appeared in JavaScript look simpler than Promise, and, of course, much more readable than callback jungle. But one thing that bothered me was the use of try-catch. At first, I thought that this was not a problem, but unfortunately I had to work with a chain of API calls, in which each API call had its own error message, which had to be checked. Soon I realized that I was creating a “try / catch jungle” that is no better than a “callback jungle”.

Let's look at this Promise, which returns data or an exception after 2 seconds, depending on the rejectPromise parameter:

// api.js const fetchData = async (duration, rejectPromise) => ( new Promise((resolve, reject) => { setTimeout(() => { if (rejectPromise) { reject({ error: 'Error Encountered', status: 'error' }) } resolve({ version: 1, hello: 'world', }); }, duration); }) ); module.exports = { fetchData, }; 

A typical use of this function would look like this:

 const { fetchData } = require('./api'); const callApi = async () => { try { const value = await fetchData(2000, false); console.info(value); } catch (error) { console.error(error); } } callApi(); /* OUTPUT: { version: 1, hello: 'world' } (rejectPromise=false) { error: 'Error Encountered', status: 'error' } (rejectPromise=true) */ 

As you can see, when the rejectPromise parameter is false, Promise returns the value {version: 1, hello: 'world'}, and when true, it raises the exception {error: 'Error Encountered', status: 'error'}.
')
This is a typical implementation of async-await. Now we will try to use Promise to make this code simpler. Let's write a wrapper function that makes it easier for us to handle exceptions.

 // wrapper.js const wrapper = promise => ( promise .then(data => ({ data, error: null })) .catch(error => ({ error, data: null })) ); module.exports = wrapper; </source   ,  -  Promise             then().catch(). ,       -: <source lang="javascript"> const { fetchData } = require('./api'); const wrapper = require('./wrapper'); const callApi = async () => { const { error, data } = await wrapper(fetchData(2000, false)); if (!error) { console.info(data); return; } console.error(error); } callApi(); /* OUTPUT: { version: 1, hello: 'world' } (rejectPromise=false) { error: 'Error Encountered', status: 'error' } (rejectPromise=true) */ 

image - we get the same result but more readable code.

Useful links.


1. Why [do not] need to use async / await

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


All Articles