Last active
January 21, 2021 07:31
-
-
Save EastSun5566/266d908c1f119fd5b4c48791f833a703 to your computer and use it in GitHub Desktop.
use async/await without try/catch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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