throwif operator
T.J. Crowder
tj.crowder at farsightsoftware.com
Tue Apr 11 12:20:21 UTC 2017
I don't think we need a new keyword for this, both because of Elie's point
about handling it with a `throwif` function, and because Node's callback
pattern is a bit old-fashioned in the world of promises and async/await.
Until the Node API is updated to support promises natively, you can use one
of the various "promisifying" libs to promisify the API:
```js
const pfs = /*...promisified version of fs*/;
```
...and then:
```js
pfs.writeFile("message.txt", "Hello Node.js")
.then(() => console.log("The file has been saved."));
```
...and like your original code snippet, it will (on recent versions)
terminate Node if you don't handle the error.
Combined with `async`/`await`, it becomes even cleaner:
```js
await pfs.writeFile("message.txt", "Hello Node.js");
console.log("The file has been saved.");
```
(Of course, that has to be within an `async` function.)
-- T.J. Crowder
On Tue, Apr 11, 2017 at 1:15 PM, Elie Rotenberg <elie at rotenberg.io> wrote:
>
const throwIf = (fn) => (err, ...args) => {
> if(err) throw err;
> return fn(...args);
> };
>
> ...
>
> fs.writeFile('message.txt', 'Hello Node.js', throwIf(() =>
> console.log('The file has been saved')));
>
>
> No need to extend the language and preempt keywords with stuff you can
> very easily implement in userland.
> I'm not even convinced such a construct would be a good idea anyway to
> encourage rethrowing errors without thinking if it can be handled locally.
>
> On Tue, Apr 11, 2017 at 2:06 PM, Нурбек <nurbek.ab at gmail.com> wrote:
>
>> An example from node.js documentation:
>>
>> fs.writeFile('message.txt', 'Hello Node.js', (err) => {
>> if (err) throw err;
>> console.log('The file has been saved!');
>> });
>>
>> This looks like a common way to handle errors when the first parameter is
>> an instance of Error.
>>
>> Yes, this line of code is short and easy to copy-paste.
>> But introducing something like this:
>>
>> fs.writeFile('message.txt', 'Hello Node.js', (err) => {
>> throwif err;
>> console.log('The file has been saved!');
>> });
>>
>> would make the code much cleaner and bring some sort of standart way to
>> handle such errors.
>>
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170411/c50c6a4e/attachment.html>
More information about the es-discuss
mailing list