承诺运行成功和失败回调



我有一系列承诺,它同时运行通过和失败回调。想不通为什么。

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

"...想不通为什么。

简单。。。因为你在打电话

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

您可能想尝试

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

当你写这个的时候

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

您立即执行这 2 个函数,而不是给出它们的引用

你应该写这样的东西

listPromise.then( pass, fail )

最新更新