Skip to content

Instantly share code, notes, and snippets.

@EastSun5566
Last active January 21, 2021 07:31
Show Gist options
  • Save EastSun5566/266d908c1f119fd5b4c48791f833a703 to your computer and use it in GitHub Desktop.
Save EastSun5566/266d908c1f119fd5b4c48791f833a703 to your computer and use it in GitHub Desktop.
use async/await without try/catch
const request = async (url) => {
const res = await fetch(url);
if (!res.ok) throw new Error(res.statusText);
return res.json()
}
// 1. HOF
// HOF to add try/catch to async function
const catch = fn => async (...params) => {
try {
return [null, await fn(...params)];
} catch (err) {
return [err];
}
}
// now can use await without try/catch
const get = catch(request);
const [err, data] = await get('https://...');
if (err) console.error(data); // handle error
// 2. Wrap promise
const to = async (promise) => {
try {
return [null, await promise];
} catch(err) {
return [err];
}
};
const [err, data] = await to(request('https://...'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment