简体   繁体   English

构建Node.js路由和API调用

[英]Structuring Node.js routing and API calls

This may be a really simple question, but I'm not sure what the most accepted way to do this is. 这可能是一个非常简单的问题,但是我不确定实现此目的的最可接受的方法是什么。

I have a route that makes an API call and then returns the result. 我有一条进行API调用然后返回结果的路由。 The problem is that the route doesn't wait for the API call to finish, but just sends the response immediately. 问题在于路由不等待API调用完成,而只是立即发送响应。

Seems like I need to structure it so that the response is fired in the callback, but I'm not exactly sure what the best practice is in this case. 似乎我需要对其进行结构设计,以便在回调中激发响应,但是我不确定在这种情况下的最佳实践。

app.get('/', function(req, res){
   var info = timesheet.getData();    // This function makes API call and
                                      // waits for response, then returns
                                      // data in callback function

   res.send(info);                    // info is undefined since this fires
                                      // before the API response is finished

});

Thanks, you guys are awesome. 谢谢,你们真棒。 John 约翰

(edited my code to be more straight forward to the question) (编辑了我的代码以更直接地回答这个问题)

does timesheet.getData accept a callback parameter? timesheet.getData接受回调参数? I would imagine it does if it is gathering data asynchronously. 我可以想象,如果它异步收集数据的话。 If it does then yes, just put your res.send in there like so: 如果是的话,是的,只需将您的res.send放在那里,就像这样:

app.get('/', function(req, res) {
    timesheet.getData(function(info) {
        res.send(info);
    }
});

If not then, well, I don't know; 如果不是,那我就不知道了。 I'll just delete this response. 我将删除此回复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM