NodeJS-使用Promises进行API调用 [英] NodeJS - using Promises for API calls

查看:75
本文介绍了NodeJS-使用Promises进行API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个nodeJS库,我在其中编码某些功能,该功能将调用SOAP API以获取信息。

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

图书馆应该处理所有幕后工作。我希望库执行的操作是首先验证给定的参数。然后根据参数(序列化?)来构造要发送的消息,创建签名等。最后,使用包含以前创建和签名的消息的soap客户端调用soap API。

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.

现在我正在考虑使用javascript Promises。我不确定是否应该包装整个library.requestThatService(parameters ...)函数以返回诺言,然后使用失败和成功函数(实践中的.then)。 我真正要问的是,应该只对实际的异步API调用还是对整个库函数使用异步?可以不向库调用返回承诺,而可以向其添加回调函数。然后在库函数中,我应该只对发送SOAP请求的部分使用异步承诺。并且不包括异步部分的验证和消息创建,因为它们不是异步操作。

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.

SOAP客户端可能已经返回了一个Promise。因此,我将有两个关于函数的承诺,而且我不确定这是否真的是个好主意。那么这些承诺之一将不会被解决或拒绝。

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.

推荐答案


我应该只使用异步是用于实际的异步API调用,还是用于整个库函数?

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?


SOAP客户端可能已经自己返回了一个承诺,您会想要使用承诺的力量吗?因此,我将有两个关于函数的承诺,而且我不确定这是否真的是个好主意。

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.

的确,在另一个新的Promise 呼叫中包装了一个返回承诺的呼叫,这是甚至是一个坏主意。

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

这篇关于NodeJS-使用Promises进行API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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