Safe Assignment

There was a good bit of buzz today about the new proposal for a safe assignment operator (?=) in JavaScript. I love how JavaScript has improved over time, but this is also a problem I've run into in a few cases lately. I should whip up a quick example implementation as a function, right?
In case you haven't read the proposal, here's what it proposes:
const [error, value] ?= maybeThrows();
The new ?= operator would be equivalent to calling the right side of the assignment in a try/catch block, returning an array. The first value of the returned array would be an error if something threw inside the assignment, and the second value would be the result of the assignment if nothing threw.
A Common try/catch Annoyance
I frequently bump into code that feels pretty ugly around assignment and try/catch blocks. Things like this:
let errorMsg;
try {
maybeThrow();
} catch (e) {
errorMsg = "An error message";
}
To access errorMsg outside of the try/catch block using const or let you have to define it outside of the block.
A Non-Async Implementation
The easiest case here is handling non-async functions. I was able to whip up
some test cases and a function called tryCatch in no time:
function tryCatch(fn, ...args) {
try {
return [undefined, fn.apply(null, args)]
} catch (e) {
return [e, undefined];
}
}
function throws() {
throw new Error("It threw");
}
// returns a sum
// prints [ undefined, 2 ]
console.log(tryCatch(Math.sqrt, 4));
// returns an error
// prints [ Error: 'It threw', undefined ]
console.log(tryCatch(throws));
tryCatch calls the function with the given arguments wrapped in a try/catch block. It appropriately returns [undefined, result] if nothing throws inside the function, and [error, undefined] if something does throw.
Note that you can use an anonymous function with tryCatch as well if you don't already have a function ready to call.
console.log(tryCatch(() => {
throw new Error("It threw");
}));
Handling Async Functions
Async functions get a little trickier. One idea I initially had was to write
a completely async version, maybe called asyncTryCatch, but where's the challenge in that. This is a completely pointless exploration! Here's an implementation of tryCatch that works with both async and non-async functions:
function tryCatch(fn, ...args) {
try {
const result = fn.apply(null, args);
if (result.then) {
return new Promise(resolve => {
result
.then(v => resolve([undefined, v]))
.catch(e => resolve([e, undefined]))
});
}
return [undefined, result];
} catch (e) {
return [e, undefined];
}
}
function throws() {
throw new Error("It threw");
}
async function asyncSum(first, second) {
return first + second;
}
async function asyncThrows() {
throw new Error("It throws async");
}
// returns a sum
// prints [ undefined, 2 ]
console.log(tryCatch(Math.sqrt, 4));
// returns an error
// prints [ Error: 'It threw', undefined ]
console.log(tryCatch(throws));
// returns a promise resolving to value
// prints [ undefined, 3 ]
console.log(await tryCatch(asyncSum, 1, 2));
// returns a promise resolving to error
// prints [ Error: 'It throws async', undefined ]
console.log(await tryCatch(asyncThrows));
It looks a lot like the original version, but with some Promise based code
thrown in for good measure. With this implementation you can call tryCatch when calling a non-async function, and then call await tryCatch when calling an async function.
Let's look at the Promise bit:
if (result.then) {
return new Promise(resolve => {
result
.then(v => resolve([undefined, v]))
.catch(e => resolve([e, undefined]))
});
}
if (result.then) checks if the given function (called with apply) returned a Promise. If it did, we need to return a Promise ourselves.
Calling result.then(v => resolve([undefined, v])) causes the promise to resolve to the value the given function returned, if nothing throws.
.catch(e => resolve([e, undefined])) is a little trickier. I originally wrote
it as .catch(e => reject([e, undefined])), but that causes an uncaught error
to fall out of tryCatch. We need to resolve here because we're returning an
array, not throwing an error.
And Finally
I pretty regularly have cases where I need to try/catch but feel like the
explicit try/catch block takes up a ton of space and is annoying for scoping assignments. I'm not sure if I'll use it or not, but this was a fun little exploration.
The above is the detailed content of Safe Assignment. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1381
52
How do I create and publish my own JavaScript libraries?
Mar 18, 2025 pm 03:12 PM
Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.
How do I optimize JavaScript code for performance in the browser?
Mar 18, 2025 pm 03:14 PM
The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.
What should I do if I encounter garbled code printing for front-end thermal paper receipts?
Apr 04, 2025 pm 02:42 PM
Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...
How do I debug JavaScript code effectively using browser developer tools?
Mar 18, 2025 pm 03:16 PM
The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.
Who gets paid more Python or JavaScript?
Apr 04, 2025 am 12:09 AM
There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.
How do I use source maps to debug minified JavaScript code?
Mar 18, 2025 pm 03:17 PM
The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.
How to merge array elements with the same ID into one object using JavaScript?
Apr 04, 2025 pm 05:09 PM
How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...
The difference in console.log output result: Why are the two calls different?
Apr 04, 2025 pm 05:12 PM
In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...


