Search code examples
bluebirdasana

Now to use Bluebird promises with Asana Node library?


I'm using the Asana Node library to create a new project with a series of sections (tasks) within the project. I need to create the sections in a specific order (synchronously) so they appear in the correct order in the project. If I just take an array of section names, then use forEach to add them as tasks, they don't appear in the correct order (because these are async calls). Here's a snippet:

var sections = [ 'Pre-Production', 'Production', 'Post-Production', 'Audio', 'Motion', 'Final' ]; sections.forEach(buildSection);

I ended up having to string together a series of .then() calls, one for each section, in order to get them built in the correct order. There's obviously a better way, but I'm new to promises and bluebird. Thanks for any help!


Solution

  • See Bluebird's Promise.reduce() for sequencing a series of operations who's data comes from an array.

    Assuming that buildSection() returns a promise when it is done and takes the section name as its argument, you could do this:

    var sections = [ 'Pre-Production', 'Production', 'Post-Production', 'Audio', 'Motion', 'Final' ]; 
    Promise.reduce(sections, function(val, item) {
        return buildSection(item);
    }, 0).then(function(finalVal) {
        // all are done here
    });
    

    Bluebird's Promise.reduce() supports the accumulated value like Array.prototype.reduce(). If you don't need that, you could also use Promise.each() or Promise.map() (with concurrency set to 1) depending upon what type of final output you might want.