总是返回承诺有用吗 [英] Is it useful to always return a promise

查看:51
本文介绍了总是返回承诺有用吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 bluebird 围绕 http 服务设计一些 nodejs api 包装器.这个包装器中的许多函数都是异步的,因此从这些实现中返回承诺是很有意义的.

I'm using bluebird to design some nodejs api wrapper around an http service. Many of the functions in this wrapper are asynchronous and so it makes a lot of sense to return promises from these implementation.

我的同事已经在这个项目上工作了几天,有趣的模式正在出现,他也在从同步实现的函数中返回承诺.

My colleague has been working on the project for a few days now and interesting pattern is emerging, he is also returning promises from synchronously implemented functions.

示例:

function parseArray(someArray){
    var result;
    // synchronous implementation
    return Promise.resolve(result);           
}

如果稍后需要使实现异步,我可以看到这将如何有用,因为您不必重构调用站点.我想所有方法始终保持异步"也很好,但我不确定这到底有多棒.

I can see how this could be useful if later on the implementation needs to be made asynchronous, as you wouldn't have to refactor the call sites. I guess it's also nice that all methods are consistently "async", but I'm not sure how awesome that exactly is.

这是否被认为是一种不好的做法,我们有什么理由不应该这样做?

Is this considered a bad practice, are there any reasons why we shouldn't do this ?

推荐答案

在同步方法中返回 promise 毫无意义.

There is no point in returning a promise in synchronous methods.

Promise 提供了对并发的抽象.当不涉及并发时,例如提供数组时.返回一个 promise 会导致更糟糕的流量控制,而且速度要慢得多.

Promises provide an abstraction over concurrency. When there is no concurrency involved such as when providing an array. Returning a promise makes for worse flow control and is considerably slower.

这也传达了错误的信息.事实上,无缘无故的承诺是一种很常见的反模式.

This is also conveying the wrong message. In fact, promisifying things with no reason is quite a common anti pattern.

有用的一种情况是,当一个方法可能是异步的——例如:从缓存中获取某些东西或在它不存在时发出请求:

One case where it is useful is when a method might be asynchronous - for example: fetching something from cache or making a request for it if it's not there:

function getData(id){
     if(cache.has(id) return Promise.cast(cache.get(id));
     return AsyncService.fetch(id).tap(cache.put);
}

这篇关于总是返回承诺有用吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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