stevendesu stevendesu - 5 months ago 29
Node.js Question

Swap order of arguments to "then" with Bluebird / NodeJS Promises

I have a function which asynchronously grabs a value from a server:

var request = require('request');
function getValue(){
return request.getAsync('')
.then(function(resp){ return resp.body; })
.catch(function(err){ thow err; });

I want to take this value and dump it to a file:

var fs = require('fs');
getValue().then(fs.writeFileAsync, "file.html");

The problem is that
expects parameter one to be the file and parameter two to be the data, but
returns the data. This is error'ing out saying:

Unhandled rejection Error: ENAMETOOLONG: name too long, open '<html....'
at Error (native)

I could circumvent this for now by writing a helper function to swap the parameters:

function myWriteFile(data, fileName) {
return fs.writeFileAsync(fileName, data);

Although if it's possible to fix this without writing a helper function that would be preferred, as I expect a lot of similar issues to arise and don't want to clutter my code with 50 helper functions. I also feel like passing data to
from a promise is probably a very common use case.


The second parameter to the .then() function is an error callback, not a parameter. Your code doesn't work at all.

Instead, you can use .bind to pre-bind a parameter:

getValue().then(fs.writeFileAsync.bind(null, "file.html"));

Note that the first parameter to .bind() is the this parameter, which doesn't matter.