Skip to content Skip to sidebar Skip to footer

Write A Promise

I have a widget and some code that opens the dialog like this $('#foo').click(); Now I need to set up some code so it run

Solution 1:

There's ample documentation on promises out in the world, but here's the skinny:

var promise = newPromise(function(resolve, reject) {
  // do a thing, possibly async, then…if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

and then:

promise.then(function(result) {
  console.log(result); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

http://www.html5rocks.com/en/tutorials/es6/promises/ that might help! good luck

Solution 2:

You need to use a Promise constructor, which will give you the ability to resolve the promise:

var p = newMyLib.Promise(function(resolver) {
    $("#foo").one("click", resolver);
}); // a promise that resolves with the next click on #foo
p.then($.fn.submit.bind($("#theForm"))); // or whatever

With jQuery, you'd need to use the Deferred pattern:

$.fn.nextEvent = function(type) {
    var d = new $.Deferred();
    this.one(type, function() {
        d.resolveWith(this, arguments);
    });
    return d.promise();
};

$("#foo").nextEvent("click").then(function(e) {
    $("#theForm").submit();
});

Post a Comment for "Write A Promise"