Jay Bienvenu
Jay Bienvenu

Reputation: 3293

Promises for getting and processing an array

I am new to both promises and having trouble understanding what I need to do to code the following logic:

I am developing a Web service in Node.js and Express to fetch song data from a wiki and return an object, which a client application will consume. The wiki's API does not let me write a batch query; I have to get each page individually. So I will have to get the list of songs, then perform a call for each song.

I currently intend to use the Q middleware for Node.js as my promises library, though I am open to suggestions on a more appropriate middleware for this task.

Here is my pseudocode:

app.get('/songs/:criteria', function(request,response) {
    downloadSongList()
    .then(foreach(song) downloadSongData)
    .then(assembleReturnValue)
    .then(response.json(returnValue));
});

What will the actual code look like?

Upvotes: 0

Views: 121

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

Here is an alternative solution with Bluebird, since you said you were interested in different libraries:

  downloadSongList(request.params).
                 map(downloadSongData).
                 call("join",",").
                 then(response.json).catch(sendError)

What we're utilizing here:

  • .map - which takes an array of promises, and calls a method on each one of them, we do that for the list returned from downloadSongList.
  • .call which calls an array method, here we're joining the elements as strings, not sure what format you're using here but this will basically do array.join.

These are some advantages we gain from Bluebird, other than that this is very similar to Bergi's answer.

Upvotes: 0

Bergi
Bergi

Reputation: 664484

The actual code will use function expressions, and around the foreach you will need to use Q.all:

app.get('/songs/:criteria', function(request,response) {
    downloadSongList(request.params)
    .then(function(list) {
        var promises = list.map(function(song) {
            return downloadSongData(song.params) // another promise
        });
        return Q.all(promises);
    }).then(function(allResults) {
        // assemble
        return // Value;
    }).then(response.json);
});

Also have a look at these general rules for promise development.

Upvotes: 3

Related Questions