问:Promisify 链式承诺的同步操作? [英] Q: Promisify Synchronous operations for chaining promises?

查看:43
本文介绍了问:Promisify 链式承诺的同步操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

promisifying 同步操作是否有任何优点,以便通过设计将它们链接到 onSuccess 或 onError 回调中?

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

例如:

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

什么是最好的?

推荐答案

不,此外,它给人的错误印象是这些方法是异步的,因此您或其他开发人员可能会调用它们并期望该方法不会破坏整个 io.js/node.js 并发模型,通过执行同步 IO.

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.

我建议您要么让这些函数不返回承诺,要么让它们执行异步 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?)

这篇关于问:Promisify 链式承诺的同步操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆