asking
asking

Reputation: 1445

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?

Upvotes: 1

Views: 694

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

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?)

Upvotes: 2

Esailija
Esailija

Reputation: 140230

Actually this particular chain will literally work exactly the same even if you wrote loadSettings like this:

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

Note that it's a horrible practice to reject with strings or throw strings so ideally you'd want new Error('No local settings!') instead. I mean just imagine if that error actually happened and it was just a string - you would have no idea how or where the error really happened.

Upvotes: 2

Related Questions