基本上,我想创建一个函数,它返回两个可以在ES6 Promise API中使用的函数。我认为它被称为“元组”。像这样:
//start code
var provider = function (a) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(a * 5);
}, 2000);
});
};
function makeProviders(num){
return [
function onResolved(){
return provider(num);
},
function onRejected(){
console.error('Dahm daniel.');
}
]
}
provider(5).then.apply(null, makeProviders(3)).then(function(val){
console.log('val => ', val);
});
//end code
然而,我得到了这个奇怪的错误:
provider(5).then.apply(null, makeProviders(3)).then(function(val){
^
TypeError: Cannot read property 'constructor' of null
at then (native)
at Object.<anonymous> (/Users/Olegzandr/WebstormProjects/oresoftware/siamese/test/test2.js:32:18)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:134:18)
at node.js:962:3
这是从正确调用另一个函数的一个函数返回两个函数的正确方法(或唯一方法)吗?
答案 0 :(得分:3)
您的问题是,您将错误的this
值传递给apply
。要工作,需要
Promise.prototype.then.apply(provider(5), makeProviders(3))
正如其他答案中所指出的,这也可以通过ES6中的扩展语法优雅地解决 但是,根据您的用例,比创建返回函数元组的函数更好的解决方案可能是将一个承诺转换为另一个承诺的函数:
function makeProviders(promise, num){
return promise.then(function onResolved(){
return provider(num);
}, function onRejected(){
console.error('Dahm daniel.');
});
}
makeProviders(provider(5), 3).…
或者更优雅地使用proposed bind operator:
function makeProviders(num){
return this.then(function onResolved(){
return provider(num);
}, function onRejected(){
console.error('Dahm daniel.');
});
}
provider(5)::makeProviders(3).…
或者,如果您想关注结果的可重用性,可以使用currying:
function makeProviders(num){
function onResolved(){
return provider(num);
}
function onRejected(){
console.error('Dahm daniel.');
}
return promise => promise.then(onResolved, onRejected);
}
var myProviders = makeProviders(3);
myProviders(provider(5)).…
答案 1 :(得分:2)
这是猜测,但我认为唯一可行的方法是使用新的点差运算符:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
我必须用Babel(我想)测试它,但答案是:
provider(5).then(...makeProviders(3)).then(function(val){
console.log('val => ', val);
});
答案 2 :(得分:1)
你必须使用“传播运营商” https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator
security.oauth2.client.client-id=my-trusted-client
security.oauth2.client.client-secret=secret
security.oauth2.client.authorized-grant-types=password,refresh_token,authorization_code,implicit
security.oauth2.client.scope=read,write,trust
security.oauth2.client.resource-ids=oauth2-resource
security.oauth2.client.access-token-validity-seconds=120
security.oauth2.client.refresh-token-validity-seconds=600