2017-06-22 22 views
1

有了這些嵌套函數:爲什麼Promise.all不一定會兌現承諾?

Promise.all(mapDomains(x => x.close())) 

我想過將它們組成:

compose(Promise.all, mapDomains)(x => x.close()) 

但是上面的代碼失敗,而不結合Promise.all本身。這是修復:

let f1 = Promise.all.bind(Promise) 
compose(f1, mapDomains)(x => x.close()) 

雖然我知道這是所有關於this關鍵字在Javascript中是如何工作的,我想知道:爲什麼不.all一定到自己了嗎?那有什麼價值嗎?

回答

0

我的猜測是這樣的問題:

var Promise = { 
 
    all: function() { 
 
    console.log(this.text) 
 
    }, 
 
    text: 'some text' 
 
}; 
 

 
Promise.all(); //some text 
 

 
function compose(f) { 
 
    f(); //Here 'this' will not be what you expect, unless you've bound it 
 
} 
 

 
compose(Promise.all); //undefined 
 
compose(Promise.all.bind(Promise)); //some text

0

您可能希望與其它無極實施

// just a demo 
 
// this should be another library to make sense 
 
class MyPromise extends Promise { 
 
    then(onFulfilled, onRejected) { 
 
    const wrappedOnFulfilled = function(arg) { 
 
     console.log(`I was fulfilled with ${arg}`) 
 
     return onFulfilled(arg) 
 
    } 
 
    return super.then.call(this, wrappedOnFulfilled, onRejected) 
 
    } 
 
} 
 

 
var all = Promise.all 
 

 
const myPromise = all 
 
    .call(MyPromise, [MyPromise.resolve(1), MyPromise.resolve(2)]) 
 
    .then(([x,y]) => console.log(x, y)) 
 

 
console.log(myPromise instanceof MyPromise)

使用