CC-Archived / promise-as3

Promises/A+ compliant implementation in ActionScript 3.0
168 stars 55 forks source link

Promise Chaining #53

Closed reyco1 closed 8 years ago

reyco1 commented 8 years ago

Can someone demonstrate a quick example on how to chain n promises? I tried to use Promise.when() but am having a hard time grasping the concept. Thanks!

honzabrecka commented 8 years ago

Just use:

fnReturingPromiseA().then(function(result:whatever):void {
  return fnReturingPromiseB(result);
}).then(function(result:whatever):void {
  return fnReturingPromiseC(result);
})

or:

fnReturingPromiseA()
   .then(fnReturingPromiseB)
   .then(fnReturingPromiseC)
reyco1 commented 8 years ago

The problem is that it could be any number of promises and I don't know that number at compile time. Basically, I have an app that can upload multiple images to a firebase database. The number of images chosen is dictated by the user, hence I can't apply the ".then" manually. I tried adding it in a loop but that does not seem to work either.

reyco1 commented 8 years ago

Figured it out... This returns the desired result:

var arr:Array = ["A", "B", "C", "D", "E"];
var s:AsynchPromise = new AsynchPromise("A");
var promise:Promise = s.execute();

for (var i:int = 1; i < arr.length; i++)
{
   var id:String = arr[i];
   var newAsynch:AsynchPromise = new AsynchPromise(id);
   promise = Promise.when(promise).then(newAsynch.execute);
}

it works the same way as doing this:

var s:AsynchPromise = new AsynchPromise("A");
s.execute()
.then(new AsynchPromise("B").execute)
.then(new AsynchPromise("C").execute)
.then(new AsynchPromise("D").execute)
.then(new AsynchPromise("E").execute)