Javascript 如何在promise join中调用新对象
我使用promise连接,我需要使用send将数据从readFile发送到myFacade(src),我的facade将obj发送到getA,后者将发送到arg[0]Javascript 如何在promise join中调用新对象,javascript,promise,bluebird,Javascript,Promise,Bluebird,我使用promise连接,我需要使用send将数据从readFile发送到myFacade(src),我的facade将obj发送到getA,后者将发送到arg[0] run = function (filePath) { return Promise.join( fs.readFileAsync(filePath, 'utf8') .then(myFacade) .then(getA), users.get
run = function (filePath) {
return Promise.join(
fs.readFileAsync(filePath, 'utf8')
.then(myFacade)
.then(getA),
users.getUsersAsync(usersObj)
.then(users.modifyRec.bind(null, process.env.us))
).then(function (args) {
return runProc('run', args[0], args[1]);
....
为了使这项工作不符合承诺,你应该做如下的事情
var parsed = new MyFacade(str);
var attribute = parsed.getA()
这是应该调用的代码
var yaml = require('yamljs');
function MyFacade(src) {
this.data = yaml.parse(src);
}
MyFacade.prototype = {
getA: function () {
return this.data.def_types.web;
},
getB: function () {
return this.data.conars;
}
};
module.exports = MyFacade;
如何使其与上面的承诺链一起工作?您正在使用
.then(getA)
这意味着“根据前面承诺的结果调用函数getA
”,但您没有函数getA
;前面承诺的结果有一个方法getA
。你想要:
至于
.then(myFacade)
有两种选择。一个是添加到构造函数中的常见内容:
function MyFacade(src) {
if(!(this instanceof MyFacade)) return new MyFacade(src);
this.data = yaml.parse(src);
}
这允许在不使用new
的情况下调用构造函数。或者,您可以将匿名函数传递给,然后
:
.then(function(str) {
return new MyFacade(str);
})
只需将您在没有承诺的情况下使用的代码作为回调传递:
return Promise.join(
fs.readFileAsync(filePath, 'utf8')
.then(function(str) {
var parsed = new MyFacade(str);
var attribute = parsed.getA()
return attribute;
}),
users.getUsersAsync(usersObj)
.then(users.modifyRec.bind(null, process.env.us)),
function(attr, rec) {
return runProc('run', attr, rec);
});
只需创建两个函数
myFacade
和getA
,分别调用new myFacade
和instance.getAt()
?谢谢,但是新关键字是什么?new myFacade(str)
return Promise.join(
fs.readFileAsync(filePath, 'utf8')
.then(function(str) {
var parsed = new MyFacade(str);
var attribute = parsed.getA()
return attribute;
}),
users.getUsersAsync(usersObj)
.then(users.modifyRec.bind(null, process.env.us)),
function(attr, rec) {
return runProc('run', attr, rec);
});