I understand that we could use .then
to make sure the order of asynchronous calls:
return doTask1()
.then(function () {
return doTask2()
})
But sometimes it will be convenient to have a light and to be able to say: wait and don't execute task2 until a light is set to GREEN; the light is a variable initially set to RED, and can be set to GREEN by task1 or other functions.
Does anyone know if it is possible to accomplish this?
Edit 1: I think being able to express this is particularly useful when we need several tasks to be ended to set the light green, and we don't know/mind the order of these tasks. .then
cannot do this easily, because we don't know the order of these tasks.
Edit 2: Regarding my light
, I had asked a more specific question. In one word, it is the message another application B sends by postMessage
that we are waiting for. At the moment, I have written the following code (which is in a resolve
), which works more or less (I have not tried if making only ONE function with their common part will work).
task1: ['codeService', '$window', '$q', function (codeService, $window, $q) {
return codeService.task1().then(function () { // task1 sends a request to another application B by postMessage
var deferred = $q.defer();
$window.addEventListener("message", function (event) {
if (event.data.req === "task1ReturnFromB") deferred.resolve(event.data)
}, { once: true });
return deferred.promise
})
}],
task2: ['codeService', 'task1', '$window', '$q', function(codeService, task1, $window, $q) {
return codeService.task2().then(function () { // task2 sends a request to Application B by postMessage
var deferred = $q.defer();
$window.addEventListener("message", function (event) {
if (event.data.req === "task2ReturnFromB") deferred.resolve(event.data)
}, { once: true });
return deferred.promise
})
}]
So in this specific case, postMessage
sent by Application B triggers the event. In a more general case, I guess we could probably trigger an event by eg, dispatchEvent, in one application?
See Question&Answers more detail:
os