基本上,我想創建一個函數,它返回兩個可以在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
這是正確的方式(或唯一辦法),從單一功能返回兩個函數用於立即調用另一個功能?
發生了什麼肯定是承諾中的promise對象(this)現在被綁定爲null,而不是承諾對象實例本身。所以看起來這種方法不起作用。 –