The Q library (https://github.com/kriskowal/q) provides very helpful adaptors for functions that follow Node's standard callback layout, i.e. last argument is function(err, result)
.
return Q.nfcall(FS.readFile, "foo.txt", "utf-8");
return Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]);
That's discussed further in the "Adapting Node" section of the README.
When using native ES6 Promises to accomplish the same, one often ends up with this unwieldy kind of trainwreck:
const fs = require('fs');
const http = require('http');
const server = http.createServer((req, res) => {
new Promise((resolve, reject) => {
fs.readFile('/etc/motd', (err, data) => {
if(err) {
reject(err.toString());
return;
}
resolve(data);
});
}).then(data => {
res.writeHead(200);
res.end(data);
}).catch(e => {
res.writeHead(500);
res.end(e);
});
}).listen(8000);
While this does flatten worst-case callback hell, it's still unwieldy and difficult to follow.
Obviously, one could decompose this into functions and inline less code to make it more readable, but that solution works fairly well for rectifying the very callback hell that promises are supposed to help solve in the first place. :-)
Is there anything I'm missing about the standard ES2015/6 Promise feature set that could allow one to save some mess here? Failing that, suggestions for low-calorie polyfills would be appreciated.
via Alex Balashov
No comments:
Post a Comment