Node.js 对微服务的REST/RPC API asyn调用
我正在为用户的请求开发许多微服务。任何图书馆都会打电话给许多其他的服务,比如帐单、推荐信 然后进行检查并回复 例: 调用一些apiNode.js 对微服务的REST/RPC API asyn调用,node.js,django,python-2.7,rabbitmq,tornado,Node.js,Django,Python 2.7,Rabbitmq,Tornado,我正在为用户的请求开发许多微服务。任何图书馆都会打电话给许多其他的服务,比如帐单、推荐信 然后进行检查并回复 例: 调用一些api get(request): // call two services async billing = billingService(user_id) //service end point 1 recommendation = recommendation_service(user_id) //service end point 2 // w
get(request):
// call two services async
billing = billingService(user_id) //service end point 1
recommendation = recommendation_service(user_id) //service end point 2
// we will have results from those two services
//check conditions response to user
if billing == OK:
response (recommendation) // response
您可以使用承诺来解决上述问题
billing = billingService(user_id).then(results => {
//Here in the results variable the output of billing service method will be stored if billing service method returns a promise.
recommendation = recommendation_service(user_id)})
Promise是javascript中处理异步调用最有效的方法
如果您专门搜索任何库,您可以使用node.js的“q”库,您可以尝试使用ES7的async/await。这样编写起来会更容易,代码看起来也会更干净 一旦开始工作,您的代码将如下所示:
const billing = await billingService(user_id)
const recommendation = await recommendation_service(user_id)
我还建议学习承诺(毕竟他们已经成功地将人们从回调地狱中解救出来)明确无误地使用async/await(因为您的billingService和Recommension_服务最终需要是异步函数才能被等待)
希望这有帮助