2016-06-01 2 views
0

Ich habe eine Reihe von Versprechen und es läuft sowohl die Pass-und Failback-Callbacks. Kann nicht herausfinden warum.Versprechen läuft sowohl Erfolg und Misserfolg Callbacks

checkForLists: function() { 
    var listCheckPromise = []; 

    $.each(scmap.lists, function(i, list) { 
     listCheckPromise[i] = $().SPServices({ 
      operation: "GetList", 
     listName: list.name, 
     }) 
    }) 

    $.map(listCheckPromise, function(listPromise, index){ 
     listPromise.then(pass(index), fail(index)) 
    }) 

    function pass(index) { 
     var currentList = scmap.lists[index] 
     console.log("PASS:", currentList.name, 'list already created') 
    } 

    function fail(index) { 
     var currentList = scmap.lists[index] 
     console.log("FAIL:", currentList.name, 'does not exist. Creating...') 
     scmap.createList(currentList) 
    } 
} 

Antwort

2

Wenn Sie schreiben diese

listPromise.then(pass(index), fail(index)) 

Sie sofort dieses Bild 2 Funktionen ausführen, anstatt ihre Referenzen geben

Sie so etwas wie dieses

listPromise.then(pass, fail) 
+0

versuchen möchten Wie würde ich den Index in diese Funktionen dann bekommen? – Batman

+0

@ Batman könnte 'bind' versuchen, dh' then (pass.bind (null, index), fail.bind (null, index)) ' – Phil

+0

Ja funktioniert gut mit Bind. Danke – Batman

3

"schreiben sollte ... Ich verstehe nicht warum. "

einfach ... weil Sie

$.map(listCheckPromise, function(listPromise, index){ 
    listPromise.then(
     pass(index), // <-- pass! 
     fail(index)) // <- and fail! 
}) 

rufen Sie wahrscheinlich

$.map(listCheckPromise, function(listPromise, index){ 
    listPromise.then(
     function(){pass(index);}, 
     function(){fail(index);}) 
}) 
+0

Okay, ich sehe, aber wenn ich es nicht so mache, wie bekomme ich den Array-Index in den Rückruf? – Batman

+0

das funktioniert auch danke – Batman

+0

Seien Sie vorsichtig, jedes Mal, wenn Sie checkForLists(), wird es im Speicher 2 anonyme Funktion erstellen() –