简体   繁体   中英

I'm struggling with a Javascript Promise

I have a tags-box, much like this site's tags-box for tagging questions.

Upon submitting my form, a JSON response allows me to show the user a dialog. In the case of this response, the dialog has some extra data, a frontendupdate (filled with fields and values to update) structure.

tags.getData() sends a JSON request to repopulate the options for the tagsbox.

And then tags.findBy() allows me to specify a "column" of tags' data and match a value to it. I'm trying to get findBy to fire AFTER getData is submitted. I know how I could do this with callbacks, but a Promise seems better here.

Unfortunately, then() seems to fire immediately after the Promise, and before the data is organized and I really don't understand why.

I've tried several variants, but clearly I'm doing something wrong.

function(dlg) {
  var id = +dlg.EXTRA.FRONTENDUPDATE.PlaceID;
  var tags = $('.tags-pTitle').data("tagsbox");

  if ($("#PlaceID").val() != id && id > 0) {
    var goal = function() {
      return new Promise(function resolve() {
        tags.getData();
        resolve();
      });
    };
    goal().then(function() {
      tags.findBy('PLACEID', id);
    });
  }
}

If tags.getData() returns a promise you can directly chain like this

function(dlg) {
  var id = +dlg.EXTRA.FRONTENDUPDATE.PlaceID;
  var tags = $('.tags-pTitle').data("tagsbox");

  if ($("#PlaceID").val() != id && id > 0) {
    tags.getData().then(function() {
      tags.findBy('PLACEID', id);
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM