I find myself using the following pattern a lot when working with json data that may or may not be corrupt:
function getFooId(json) {
const id = json.foo.id;
if (!id) {
throw Error(`foo.id has not been defined`);
}
return id;
}
This seems overly verbose. I would like a one-liner along the lines of:
function getBarId(json) {
return json.bar.id? json.bar.id : throw Error(`bar.id has not been defined`);
}
Can this be done?
There's a proposal for throw expressions that would allow you to do this really concisely, but it's still at stage 2 - it hasn't been implemented yet.
Currently, throw
must be a statement , like an if
statement or a function declaration - it can't be in an expression context. To achieve this, you could alternate the id
variable with an IIFE, where the first (and only) line of the IIFE throws;
function getBarId({ bar: { id }}) {
return id || (() => { throw new Error(`bar.id has not been defined`); })();
}
But I still prefer your first method, it's more readable:
function getBarId({ bar: { id }}) {
if (id) return id;
throw new Error(`bar.id has not been defined`);
}
This also a better way to handle the error
function getBarId({bar:{id}}) {
return new Promise((resolve,reject)=>{ id ? resolve(id) : reject(`bar.id has not
been defined`)})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.