var promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
console.log('Promise resolved');
}, 5000);
});
var deferred = $.Deferred();
setTimeout(function () {
deferred.resolve();
console.log('Deferred resolved');
}, 10000);
Promise.all([promise,deferred]).then(function () {
console.log('All is done');
});
function getMyPhoto(tag, handlerCallback) {
asyncGet('login_url', function () {
asyncGet('photo_url', function() {
asyncGet('photo_details', function(neededResult) {
handlerCallback(neededResult);
});
});
});
}
getMyPhoto('puppy', drawOnScreen); login().then(getPhoto).then(getPhotoDetails).then(render);var p = new Promise(function(resolve, reject) {
resolve(1);
resolve(2);
});
Promise.all([p]).then(function (value) {
console.log(value);
});
var p = new Promise(function (resolve, reject) {
if (isSomeThingTrue){
resolve(amResolvedValue);
} else {
reject(amRejectedValue);
}
});
p.then(function (value) {
console.log(value);
});
Promise.prototype.then(fulfillCallback, rejectCallback)
Return a promise p such that:
if fulfillCallback is undefined
p will be fulfilled with o when this promise is fulfilled with o.
if rejectCallback is undefined
p will be rejected with o when this promise is rejected with o
p will be fulfilled with fulfillCallback(o) when this promise is fulfilled with o.
p will be fulfilled with rejectCallback(o) when this promise is rejected with o.
p will be rejected with e if fulfillCallback or rejectCallback throws e.
Promises/A and Promises/A+
Известные Promises/B применения: Q и whenthen.js
return Q.fcall(function () {
return [{ foo: "bar" }, { foo: "baz" }];
})
.get(0)
.get("foo");
makePromise(promise).get('lists').get('0').get('items').then(displayIt);
doFailingAsync().then(function() {
// doFailingAsync doesn't succeed.
}, function(error) {
// Try to handle the error.
return "It's all good.";
}).then(function(result) {
// Non-jQuery implementations will reach this with result === "It's all good.".
}, function(error) {
// jQuery will reach this with error === "It's all good.".
});promise.then(function (x) { // Suppose promise returns "abc"
console.log(x);
return 123;
}).then(function (x){
console.log(x);
}).then(function (x){
console.log(x)
});
Console:
abc 123 undefined
promise.done(function (x) { // Suppose promise returns "abc"
console.log(x);
return 123;
}).done(function (x){
console.log(x);
}).done(function (x){
console.log(x)
})
Console:
abc abc abc
var promise = new RSVP.Promise(function(resolve, reject) {
// succeed
resolve(value);
// or reject
reject(error);
});
promise.then(function(value) {
// success
}, function(value) {
// failure
});
var object = {};
RSVP.EventTarget.mixin(object);
object.on("finished", function(event) {
// обрабатываем событие
});
object.trigger("finished", { detail: value });