NodeJS - using Promises for API calls

早过忘川 提交于 2019-12-11 06:45:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/38866725/nodejs-using-promises-for-api-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!