Is it useful to always return a promise

后端 未结 2 1052
无人及你
无人及你 2020-12-06 14:00

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 retur

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 14:06

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

    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);
    }
    

提交回复
热议问题