In domain-task, ensure completion callback always fires asynchronously

This commit is contained in:
SteveSandersonMS
2016-03-07 15:27:56 +00:00
parent c44ceebc12
commit b95cd1bc85
2 changed files with 11 additions and 6 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "domain-task", "name": "domain-task",
"version": "1.0.0", "version": "1.0.1",
"description": "Tracks outstanding operations for a logical thread of execution", "description": "Tracks outstanding operations for a logical thread of execution",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {

View File

@@ -9,14 +9,17 @@ export function addTask(task: PromiseLike<any>) {
state.numRemainingTasks++; state.numRemainingTasks++;
task.then(() => { task.then(() => {
// The application may have other listeners chained to this promise *after* // The application may have other listeners chained to this promise *after*
// this listener. Since we don't want the combined task to complete until // this listener, which may in turn register further tasks. Since we don't
// all the handlers for child tasks have finished, delay the following by // want the combined task to complete until all the handlers for child tasks
// one tick. // have finished, delay the response to give time for more tasks to be added
// synchronously.
setTimeout(() => { setTimeout(() => {
state.numRemainingTasks--; state.numRemainingTasks--;
if (state.numRemainingTasks === 0 && !state.hasIssuedSuccessCallback) { if (state.numRemainingTasks === 0 && !state.hasIssuedSuccessCallback) {
state.hasIssuedSuccessCallback = true; state.hasIssuedSuccessCallback = true;
state.completionCallback(/* error */ null); setTimeout(() => {
state.completionCallback(/* error */ null);
}, 0);
} }
}, 0); }, 0);
}, (error) => { }, (error) => {
@@ -42,7 +45,9 @@ export function run<T>(codeToRun: () => T, completionCallback: (error: any) => v
// If no tasks were registered synchronously, then we're done already // If no tasks were registered synchronously, then we're done already
if (state.numRemainingTasks === 0 && !state.hasIssuedSuccessCallback) { if (state.numRemainingTasks === 0 && !state.hasIssuedSuccessCallback) {
state.hasIssuedSuccessCallback = true; state.hasIssuedSuccessCallback = true;
state.completionCallback(/* error */ null); setTimeout(() => {
state.completionCallback(/* error */ null);
}, 0);
} }
} catch(ex) { } catch(ex) {
state.completionCallback(ex); state.completionCallback(ex);