Q: Promisify Synchronous operations for chaining promises?

对着背影说爱祢 提交于 2020-01-05 07:53:08

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/30159316/q-promisify-synchronous-operations-for-chaining-promises

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!