locked
Sequential chaining of work from array using Promises

    Question

  • Given this array of Strings 

    ids = ["1", "2", "3"]

    I want to run through that array and call an Async function with the entry like this

    entry = ids[0]

    doAsync(entry).done(function(result) {
      ids.pop();
      // loop again, get first entry
    }, function(error) {});

    Can this be done without recursion?

    Wednesday, June 27, 2012 9:11 PM

Answers

  • Yes, this can be done without recursion in a couple of different ways, I prefer the first for collections of known length, or the last for collections of unknown length:

    var ids = ['1', '2', '3'];


    // If you want them to run one after the other
    //
    var result =
        ids.reduce(
            function (p, id) {
                return p.then(function () {
                    return myAsyncFunction(id);
                });
            },
            WinJS.Promise.wrap()
        );

     

    // If you want them to run all at the same time:
    //
    var result = WinJS.Promise.join(ids.map(myAsyncFunction));


    // If you want to write the recursive code but introduce asynchrony to
    //  avoid stack recursion
    //
    var pos = 0;
    function process() {
        if (pos < ids.length) {
            var id = ids[pos++];
            return myAsyncFunction(id)
                .then(function () {
                    return WinJS.Promise.timeout();
                })
                .then(process);
        }
    }
    var result = process();

    Thursday, June 28, 2012 6:30 PM

All replies

  • Yes, this can be done without recursion in a couple of different ways, I prefer the first for collections of known length, or the last for collections of unknown length:

    var ids = ['1', '2', '3'];


    // If you want them to run one after the other
    //
    var result =
        ids.reduce(
            function (p, id) {
                return p.then(function () {
                    return myAsyncFunction(id);
                });
            },
            WinJS.Promise.wrap()
        );

     

    // If you want them to run all at the same time:
    //
    var result = WinJS.Promise.join(ids.map(myAsyncFunction));


    // If you want to write the recursive code but introduce asynchrony to
    //  avoid stack recursion
    //
    var pos = 0;
    function process() {
        if (pos < ids.length) {
            var id = ids[pos++];
            return myAsyncFunction(id)
                .then(function () {
                    return WinJS.Promise.timeout();
                })
                .then(process);
        }
    }
    var result = process();

    Thursday, June 28, 2012 6:30 PM
  • Thanks Josh. And what about a queue like array that can get new elements pushed into it while working on the items in the array?
    Wednesday, July 04, 2012 7:40 PM