Search code examples
javascriptnode.jspromisechaining

Accomplish Promise Chaining


Background

I have a nodejs server running and I installed the promise package which follows the promise api specs.

Since I succeeded in making denodeify(fn, length) work, I am now in the process of chaining promises, but I am failing to grasp the main concepts.

What I tried

By reading the documentation example on the specification page, I reached the following code:

let Promise = require("promise");
let write = Promise.denodeify(jsonfile.writeFile);
let read = Promise.denodeify(jsonfile.readFile);

read("dataFile.txt").then( () => {
    write("./testFile.txt", "hello_World", TABS_FORMATTING).then(console.log("file complete"));
});

Which is quite different from the examples I see, for example, in the Solutions Optimist tutorial:

 loadDeparture( user )
        .then( loadFlight )
        .then( loadForecast );

Objective

My objective is to make my code as beautiful as the example I showed before, but I don't understand how I can make as concise as it is right now.

Question

1 - What changes do I need to perform in my code to achieve that level?


Solution

  • The given example uses named function to make it look as good as it can get, but that can be a bit redundant because then you're creating functions for every little thing in the chain. You must pick and choose when to use named functions over anonymous functions.

    One thing you must also realize is that to chain promises you must return them. So to make it a proper chain you must return the write method so it is passed down to the next step.

    Also make sure that the catch() method is used at the bottom of every promise chain so that errors aren't silently swallowed.

    Note that in the example here I'm using the ES2015 arrow functions to return the write() method as that makes it looks better(which seemed to be the purpose of your question).

    let Promise = require("promise");
    let write = Promise.denodeify(jsonfile.writeFile);
    let read = Promise.denodeify(jsonfile.readFile);
    
    read("dataFile.txt")
        .then(() => write("./testFile.txt", "hello_World", TABS_FORMATTING))
        .then(results => console.log("file complete", results))
        .catch(error => console.error(err));
    

    I'd recommend reading this article for some best practices.