为什么这个承诺不能正常工作?

时间:2014-10-22 15:30:31

标签: javascript jquery promise

我是jQuery Promises的新手,但我在应用程序的其他部分使用它们很好,但是这个似乎没有按预期工作。似乎在执行下一个代码之前它没有等待返回。

function setActivityOnGrid(){
...snip...
var sameActivityCnt = $(actId).length;
  if(sameActivityCnt){
    sameActivityDialog().then(function(retVal) {
      if(retVal == true){
        activityid += "-"+sameActivityCnt++;
      }
    });
}
//code here is being executed before the dialog is even shown
}

function sameActivityDialog(){
  var deferred = $.Deferred();

  bootbox.confirm("You have already added this activity. Would you like to add it again?", function(result) {
    deferred.resolve(result);
  });
  return deferred.promise();
}

2 个答案:

答案 0 :(得分:2)

//code here is being executed before the dialog is even shown移至此处:

var sameActivityCnt = $(actId).length;
if(sameActivityCnt){
  sameActivityDialog().then(function(retVal) {
    if (retVal === true){
      activityid += "-"+sameActivityCnt++;
    }

    // code goes here!!!!

  });
}

在then回调函数内部(或稍后链接然后函数)。

替代

var sameActivityCnt = $(actId).length;
sameActivityDialog().then(function(retVal) {
  if(sameActivityCnt && retVal === true){
    activityid += "-"+sameActivityCnt++;
  }

  // code goes here!!!!

});

var promise = sameActivityDialog();
var sameActivityCnt = $(actId).length;

if(sameActivityCnt){
  promise = promise.then(function(retVal) {
    if (retVal === true){
      activityid += "-"+sameActivityCnt++;
    }
    return retVal;
  });
}

promise = promise.then(function(retVal) {
  // code goes here!!!!
  return retVal;
});

如果你将这个逻辑分成更小的函数,那么你实际上可以很好地编写这个:

function doIf(condition, fn) {
  return function(data) {
    if (condition) {
      return fn(data);
    } else {
      return data
    }
  };
}

function appendID(retVal) {
  if (retVal === true){
    activityid += "-"+sameActivityCnt++;
  }
  return retVal;
}

function doMoreStuff(retVal) {
  // code goes here!!!!
  return retVal;
}

var sameActivityCnt = $(actId).length;

sameActivityDialog()
  .then(doIf(sameActivityCnt, appendID))
  .then(doMoreStuff);

答案 1 :(得分:1)

承诺正常运作。承诺不会构成非阻塞功能块。

它为您提供了一个对象,您可以重复添加将在非阻塞函数完成时运行的新回调。