[英]passing parameters to functions returning promises in a chain
I've a bunch of functions expecting parameters and returning promises, not sure how can I pass individual params to each one in the chain. 我有一堆函数期望参数并返回promise,但不确定如何将各个参数传递给链中的每个参数。
fs.readFile('./img/thumbnail.png', function(error, data) {
module.create(body)
.then(module.uploadImage) //expects collection.uploadImage(data);
.then(module.requestInfo)
});
How can I make promises pass data
to module.uploadImage
as the parameter? 我怎样才能保证将data
作为参数传递给module.uploadImage
?
If the data is known at the time you enter the function, you can use .bind()
: 如果在输入函数时知道数据,则可以使用.bind()
:
fs.readFile('./img/thumbnail.png', function(error, data) {
module.create(body)
.then(module.uploadImage.bind(module, data))
.then(module.requestInfo)
});
See the description of .bind()
on MDN for more details. 有关更多详细信息,请参见MDN上.bind()
的描述 。
You can of course, always just create your own wrapper function that lets you pass anything you want, including computed parameters: 当然,您始终可以创建自己的包装函数,使您可以传递所需的任何内容,包括计算参数:
fs.readFile('./img/thumbnail.png', function(error, data) {
module.create(body).then(function() {
return module.uploadImage(data);
}).then(module.requestInfo)
});
PS Please don't ignore error checking on your fs.readFile()
callback. PS:请不要忽略对fs.readFile()
回调进行的错误检查。
Use anonymous function: 使用匿名功能:
fs.readFile('./img/thumbnail.png', function(error, data) {
module.create(body)
.then(function(){ module.uploadImage(data); }) //expects collection.uploadImage(data);
.then(module.requestInfo)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.