[英]passing parameters to functions returning promises in a chain
我有一堆函数期望参数并返回promise,但不确定如何将各个参数传递给链中的每个参数。
fs.readFile('./img/thumbnail.png', function(error, data) {
module.create(body)
.then(module.uploadImage) //expects collection.uploadImage(data);
.then(module.requestInfo)
});
我怎样才能保证将data
作为参数传递给module.uploadImage
?
如果在输入函数时知道数据,则可以使用.bind()
:
fs.readFile('./img/thumbnail.png', function(error, data) {
module.create(body)
.then(module.uploadImage.bind(module, data))
.then(module.requestInfo)
});
有关更多详细信息,请参见MDN上.bind()
的描述 。
当然,您始终可以创建自己的包装函数,使您可以传递所需的任何内容,包括计算参数:
fs.readFile('./img/thumbnail.png', function(error, data) {
module.create(body).then(function() {
return module.uploadImage(data);
}).then(module.requestInfo)
});
PS:请不要忽略对fs.readFile()
回调进行的错误检查。
使用匿名功能:
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.