by flavio81 · 9y ago · 0 comments
Node.js 8.0.0 includes a new util.promisify() API that allows standard Node.js callback style APIs to be wrapped in a function that returns a Promise. An example use of util.promisify() is shown below.
This is great stuff. This enables writing code using async and await at all times, which is what any sane developer would do when writing code for Node.js.
const promisify = (fn, ctx) => (...args) =>
new Promise((resolve, reject) =>
fn.apply(ctx, [ ...args,
(err, data) => err ? reject(err) : resolve(data)
])
)[1]: https://nodejs.org/api/util.html#util_util_promisify_origina...
[2]: https://github.com/nodejs/node/blob/ef16319effe396622666268c...
Having a stdlib function makes for an easy "let's just use this everywhere" answer.
somePromise.then(function() {
return a.b.c.d();
}).catch(TypeError, ReferenceError, function(e) {
//Will end up here on programmer error
}).catch(NetworkError, TimeoutError, function(e) {
//Will end up here on expected everyday network errors
}).catch(function(e) {
//Catch any unexpected errors
});
It's super useful. Sometimes you want to catch two different sorts of exception. You could do something like
f = expr `catch` \ (ex :: ArithException) -> handleArith ex
`catch` \ (ex :: IOException) -> handleIO ex
However, there are a couple of problems with this approach. The first is that having two exception handlers is
inefficient. However, the more serious issue is that the second exception handler will catch exceptions in the
first, e.g. in the example above, if handleArith throws an IOException then the second exception handler will
catch it.
Instead, we provide a function catches, which would be used thus:
f = expr `catches` [Handler (\ex :: ArithException -> handleArith ex),
Handler (\ex :: IOException -> handleIO ex)] .catch(ArithException, IOException, handleError)
Edit: Nevermind, I think what you want to be able to do is provide two different error handlers, but essentially catch them at the same time so that if you throw inside one of them, the second one wouldn't catch it.As a matter of fact, does anyone have a benchmark of the new nodejs 8's promise implementation against bluebird, because I so far bluebird was faster than the native implementation.
[0]: https://medium.com/@styfle/promises-in-node-js-8-x-core-d6a8...
function logAppendResult( err ) {
if (err) console.err('Failed to update file');
else console.log('Successfully updated file');
}
function logWriteResult( err ) {
if (err) console.err('Failed to create file');
else console.log('Successfully created file');
}
function handleFile( filename, fileExists ) {
const timestamp = new Date().toISOString();
( fileExists )
? fs.appendFile( filename, `Updated file on ${timestamp}\n`, logAppendResult )
: fs.writeFile( filename, `Created file on ${timestamp}\n`, logWriteResult );
}
function main() {
const filename = './example.txt';
exists( filename, (fileExists) => handleFile(filename, fileExists) );
}Well, who are we to deprive you from the joy of writing lots of boilerplate code?
(There are lots of other reasons to use the promise abstraction – having a type that can be transformed is extremely useful and natural – but that one’s pretty significant.)
if (err) console.err('Failed to create file');
Congratulations, you're writing Go in JavaScript! :)The real value for promises is async/await.
You've repeated the if(err) check in three places.
None of your error handling bubbles up so the handlers (i.e. Logging to console.error) are buried in the individual functions.
You've pretended to avoid nested callbacks by inlining them using arrow functions.
For your sake I hope that was sarcastic.
Inlining with arrows is just a more functional approach, as I would write in Coffee:
exists filename, (fileExists) -> handleFile filename, fileExists
Anything wrong with that line of code?I just try very hard to keep my code as simple as possible.
I hope you know it's trivial to write a log function that accepts different callees so you end up with only 1 'if (err)'.
I didn't test, but I wouldn't be surprised if my example runs times faster as well btw.
Using `try`/`catch` with `async`/`await` is a bit awkward, though, which is especially unfortunate because it's the #1 place you should be handling errors.
LightScript has a language feature[0] that makes it less awkward (sort of an`Either`/`Result` type) that I'm thinking about submitting to TC39.
If you started programming with Node, it's like you've learned doing everything the wrong way.
The async/await brings back the sane, synchronous, reasoning. There's a reason that from Lisp to Haskell, every language tried to get rid of the error-prone callback spaghetti.
A sync await is an argument for people like you, who are trying hard to change its nature. It was added to the specs, because of "browsers got stuck to JavaScript".
There are better server side languages, so you can use them.
You can hardly escape from imperative code except without syntactic sugar either. That doesn't mean that one should program in the lower layer of abstraction of a platform. If we followed that, C programming would be all gotos instead of functions and the usual control flow (even "if" and "for" are syntactic sugar on top of assembly constructs).
>A sync await is an argument for people like you, who are trying hard to change its nature.
If it wasn't for people who tried hard to change its nature, JS would still be the same ho-hum language it was its first 15 years (I was there). Node.js was itself an attempt to "change" the nature of JS, moving it from client to server side.
The need for callbacks stems from the fact that JS as a language was never specifically event oriented -- any more than in any other language. It just supported DOM events in the browser environment, which for the first 10-15 years of the web were just simple one level callback handler (button clicked, do that). Hardly any kind of asynchronous programming to write home about. Aside from having first class functions, JS was not particularly designed for evented code. That's where callbacks came in, as a poor man's way to deal with evented code -- other languages have had coroutines, promises etc for 30+ years.
You never need use use async / await.
> This enables writing code using async and await at all times, which is what any sane developer would do when writing code for Node.js.