Ville Miekk-oja Ville Miekk-oja - 3 months ago 30
Node.js Question

NodeJS - using Promises for API calls

I have a nodeJS library, where I'm coding a certain functionality, which will call a SOAP API to get information.

I want that people can use the library easily. So that they can just call:

library.requestThatService(parameters ...);


And the library should handle all the dirty work behind scenes. What I want the library to do is to first possibly validate the parameters given. Then construct the message to be sent based on the parameters (serialization?), create signature etc... And finally, call the soap API with a soap client including the message created and signed before.

Now I'm thinking of using javascript Promises for that. I'm not sure whether I should wrap the whole library.requestThatService(parameters ...) function to return a promise, and then use fail and success function (.then in practise). What I'm really asking is, that whether I should only use async for the actual async API call, or for the whole library function? Instead of making the library call to return a promise, I could add a callback function to it. Then inside the library function, I should use async promises only for the part where the SOAP request is sent. And not include validation and message creation for the async part, since they are not async operations.

The SOAP client might return a promise by itself already. So then I would have two promises floating around a function, and I'm not sure if that is a good idea at all really. Then one of those promises wouldn't be resolved or rejected.

Answer

Should I only use async for the actual async API call, or for the whole library function?

Yes - always promisify at the lowest level! You will want to use power of promises yourself, don't you?

The SOAP client might return a promise by itself already. So then I would have two promises floating around a function, and I'm not sure if that is a good idea at all really.

Indeed, wrapping a promise-returning call in another new Promise call is an exceptionally bad idea even.

Comments