将参数的顺序交换为"then"与Bluebird/NodeJS的承诺 [英] 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');
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");
问题是fs.writeFileAsync
希望参数1是文件,而参数2是数据,但是getValue()
返回数据.这是错误的说法:
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);
}
尽管有可能在不编写首选的辅助函数的情况下解决此问题,因为我希望会出现很多类似的问题,并且不想将50个辅助函数弄乱我的代码.我还觉得从诺言将数据传递到writeFile
可能是一个非常常见的用例.
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.
推荐答案
.then()
函数的第二个参数是错误回调,而不是参数.您的代码根本不起作用.
The second parameter to the .then()
function is an error callback, not a parameter. Your code doesn't work at all.
相反,您可以使用.bind
预先绑定参数:
Instead, you can use .bind
to pre-bind a parameter:
getValue().then(fs.writeFileAsync.bind(null, "file.html"));
请注意,.bind()
的第一个参数是this
参数,这无关紧要.
Note that the first parameter to .bind()
is the this
parameter, which doesn't matter.
这篇关于将参数的顺序交换为"then"与Bluebird/NodeJS的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!