0

I have a function which calls dealCardSelectableAI(), which sets up a number of jQuery deferred promises. The function setCardName() is then called from within it. Once both functions complete their tasks saveGame() should then be triggered.

Everything works, except setCardName() does not complete before saveGame() is triggered. It appears that deferredQueue.push(setCardName(system, result)); is not operating as I expected. I am not sure where I'm going wrong or how to resolve the issue.

var setCardName = function (system, card) {
  var deferred = $.Deferred();

  require(["cards/" + card[0].id], function (data) {
    var cardName = loc(data.summarize());
    system.star.ai().cardName = ko.observable(cardName);
    deferred.resolve();
  });
  return deferred.promise();
};

var dealCardSelectableAI = function (win, turnState) {
  var deferred = $.Deferred();

  // Avoid running twice after winning a fight
  if (!win || turnState === "end") {
    var deferredQueue = [];

    _.forEach(model.galaxy.systems(), function (system, starIndex) {
      if (
        model.canSelect(starIndex) &&
        system.star.ai() &&
        system.star.ai().treasurePlanet !== true
      ) {
        deferredQueue.push(
          chooseCards({
            inventory: inventory,
            count: 1,
            star: system.star,
            galaxy: game.galaxy(),
            addSlot: false,
          }).then(function (result) {
            deferredQueue.push(setCardName(system, result));
            system.star.cardList(result);
          })
        );
      }
    });

    $.when(deferredQueue).then(function () {
      deferred.resolve();
    });
  } else {
    deferred.resolve();
  }

  return deferred.promise();
};

dealCardSelectableAI(false).then(saveGame(game, true));
3
  • You are calling save game and what it returns is set to the then. It is not calling saveGame when then is triggered. Commented Jan 3, 2022 at 16:35
  • 1
    deferredQueue.push(setCardName(system, result)); is executed asynchronously, and won't be considered by $.when. Instead, use promise chaining Commented Jan 3, 2022 at 17:52
  • Does the promise chain need to live within the chooseCards() chain, or be chained to the dealCardSelectableAI() call? Commented Jan 3, 2022 at 18:52

1 Answer 1

1

Your code says call saveGame() and what is returned from the function call should be set to then. It is not saying, "call saveGame when done"

dealCardSelectableAI(false).then(function () { saveGame(game, true) });
Sign up to request clarification or add additional context in comments.

1 Comment

Gah! What a derp. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.