// 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, };
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) */
// 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) */
Source: https://habr.com/ru/post/358896/
All Articles