2017-06-22 2 views
1

Mit diesen verschachtelten Funktionen:Warum Promise.all ist nicht verpflichtet, zu versprechen?

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

Ich dachte daran, sie zu komponieren:

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

jedoch oberhalb der Code nicht ohne Promise.all an sich zu binden. Dies ist das Update:

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

Obwohl ich verstehe, es ist alles darüber, wie das this Schlüsselwort arbeitet in Javascript, frage ich mich: Warum ist .all nicht schon an sich selbst begrenzt? Gibt es irgendeinen Wert darauf?

Antwort

0

Meine Vermutung ist, so etwas wie das ist das Problem:

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

Man könnte es mit einem anderen Versprechen Implementierung verwenden möchten

// 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)

Verwandte Themen