Search code examples
promiseqchaining

Q: Promisify Synchronous operations for chaining promises?


Is there any merit in promisifying synchronous operations so that by design they can be chained in onSuccess or onError callbacks?

Eg:

function loadSettings(path) {
    if (fs.existsSync(path)) {
        return Q(fsJson.loadSync(path));
    }
    return new Q.defer().reject('No local settings!');
}

doingSomethingFirst()
    .then(loadSettings, obtainSettings)
    .then(doSomethingWithSettings)
    .done()

What's best?


Solution

  • No, moreover, it gives the false impression that these methods are async so you or other developers might call them and expect that the method is not undermining the entire io.js/node.js concurrency model by performing sync IO.

    I recommend that you either make these functions not return promises or make them perform async IO. Also note that your method has a race condition (what if the file is deleted between when you check it exists and when you try to access it?)