Recently I wrote about using Node.js with Swagger to build a simple listener for the Sync Gateway changes feed. In that version I did everything using synchronous calls. I’m working to build a more complete solution, so I decided to switch over to using Promises. I opted to use the Bluebird Promises library. Bluebird has some nice features over the built-in version.
The Problem
I ran into one problem that took me a little while to solve. Bluebird has a handy function return
. It’s just shorthand for creating a Promise that resolves to the given value. You use it like this:
1 2 |
doSomething() .return("Unrelated value"); |
When I used this, though, I kept getting errors:
1 |
TypeError: doSomething().return is not a function |
This was really puzzling at first, since more complicated constructions were working fine.
The Solution
Bluebird is built to drop in and replace the standard Promises implementation. However, the Swagger JS client uses the Q Promises library explicitly.
This means promises returned by my calls to the Sync Gateway endpoints were getting replaced by the Q version. Since Bluebird and Q share much of their core API, it took some digging to realize what was happening.
There are a few ways to address this. Since return
is such a simple routine, I just decided to stick with using the equivalent then
call.
Here are a few alternatives to try if you want:
promisifyAll
Swagger instead of using Swagger’s built-in support- Use the “bluebird-q” project to replace Q with Bluebird
- Wrap calls with
Promise.resolve()
Postscript
Check out more resources on our developer portal and follow us on Twitter @CouchbaseDev.
You can post questions on our forums. And we actively participate on Stack Overflow.
You can follow me personally at @HodGreeley.