4 ms·
Or post ES2017, without all the .then()s: const doThing = async (url, fallback) => { try { const response = await fetch(url) const notificati
by nailer 4y ago
Or post ES2017, without all the .then()s:
const doThing = async (url, fallback) => {
try {
const response = await fetch(url)
const notifications = await response.json()
return notifications.map((notification) => ({
...notification,
readableDate: new Date(notification.date * SECONDS).toGMTString(),
message: notification.message.replace(/</g, '<'),
sender: `https://example.com/users/${notification.username}`,
source: `https://example.com/${notification.sourceType}/${notification.sourceId}`,
icon: `https://example.com/assets/icons/${notification.sourceType}-small.svg`,
}))
} catch (error) {
console.log(error.message);
return fallback
}
}
- still_grokking 4y agoIs this code really equivalent? Wouldn't it block on the `await` calls, whereas the original code would instantly pass control back to the caller? (Sorry if this question is odd. My JS is a little bit rusted).
- LegionMammal978 4y agoIt's an async arrow function, which means that it returns a `Promise` when called, much like the original code that constructs a `Promise` explicitly. This `Promise` resolves once the function returns.
- still_grokking 4y agoThanks for the prompt answer! I've overlooked the `async` on the first line… My fault. :-|
- 0x445442 4y agoI’m JS illiterate but I think control is returned to the main thread until the await call returns, at which time the execution continues.
- still_grokking 4y agoJS is single threaded. Async / await is just a code transformation that introduces Promise wrappers. The code should be equivalent to the original. (I've just overlooked the top-level `async`…).
- adamwk 4y agoAnd now we’ve gone full circle to writing imperative code