Swap order of arguments to “then” with Bluebird /

2019-09-15 12:00发布

问题:

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

var request = require('request');
Promise.promisifyAll(request);
function getValue(){
    return request.getAsync('http://www.google.com')
        .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');
Promise.promisifyAll(fs);
getValue().then(fs.writeFileAsync, "file.html");

The problem is that fs.writeFileAsync expects parameter one to be the file and parameter two to be the data, but getValue() 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 writeFile from a promise is probably a very common use case.

回答1:

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.