Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure that callbacks are always executed asynchronously. #86

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
52 changes: 34 additions & 18 deletions when.js
Expand Up @@ -188,11 +188,15 @@ define(function () {
*/
function fulfilled(value) {
var p = new Promise(function(onFulfilled) {
try {
return resolve(typeof onFulfilled == 'function' ? onFulfilled(value) : value);
} catch(e) {
return rejected(e);
}
var deferred = defer();
setTimeout(function() {
try {
deferred.resolve(typeof onFulfilled == 'function' ? onFulfilled(value) : value);
} catch(e) {
deferred.reject(e);
}
}, 0);
return deferred.promise;
});

return p;
Expand All @@ -208,11 +212,15 @@ define(function () {
*/
function rejected(reason) {
var p = new Promise(function(_, onRejected) {
try {
return resolve(typeof onRejected == 'function' ? onRejected(reason) : rejected(reason));
} catch(e) {
return rejected(e);
}
var deferred = defer();
setTimeout(function() {
try {
deferred.resolve(typeof onRejected == 'function' ? onRejected(reason) : rejected(reason));
} catch(e) {
deferred.reject(e);
}
}, 0);
return deferred.promise;
});

return p;
Expand Down Expand Up @@ -277,13 +285,15 @@ define(function () {

progressHandler = typeof onProgress === 'function'
? function(update) {
try {
// Allow progress handler to transform progress event
deferred.progress(onProgress(update));
} catch(e) {
// Use caught value as progress
deferred.progress(e);
}
setTimeout(function() {
try {
// Allow progress handler to transform progress event
deferred.progress(onProgress(update));
} catch(e) {
// Use caught value as progress
deferred.progress(e);
}
}, 0);
}
: function(update) { deferred.progress(update); };

Expand Down Expand Up @@ -638,7 +648,13 @@ define(function () {
var handler, i = 0;

while (handler = queue[i++]) {
handler(value);
setTimeout(handle(handler), 0);
}

function handle(handler) {
return function() {
return handler(value);
};
}
}

Expand Down