如何等待请求响应并返回值?

编程入门 行业动态 更新时间:2024-10-23 15:17:30
本文介绍了如何等待请求响应并返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我在 node.js 服务器中使用请求模块时,我遇到了一些问题,例如等待和返回.

When I use a request module in node.js server, I have some problem such as wait and return.

我想在 requestController 中接收一个responseObject"值.

I would like to receive a "responseObject" value at requestController.

为了解决这个问题,我已经搜索了最好的方法,但还是没有找到.

To solve this problem, I have search the best way but I still do not find it.

如何解决这个问题?

提前致谢!!:)

============================================================================

=========================================================================

var requestToServer = require('request'); function getRequest(requestObject) { var urlInformation = requestObject['urlInformation']; var headerInformation = requestObject['headerInformation']; var jsonObject = new Object( ); // Creating the dynamic body set for(var i = 0; i < headerInformation.length; i++) jsonObject[headerInformation[i]['headerName']] = headerInformation[i]['headerValue']; requestToServer({ url : urlInformation, method : 'GET', headers : jsonObject }, function(error, response ,body) { // todo response controlling var responseObject = response.headers; responseObject.body = body; }); } // Controlling the submitted request exports.requestController = function(requestObject) { var method = requestObject['methodInformation']; var resultObject = null; // Selecting the method if(method == "GET") resultObject = getRequest(requestObject); else if(method =="POST") resultObject = postRequest(requestObject); else if(method == "PUT") resultObject = putRequest(requestObject); else if(method == "DELETE") resultObject = deleteRequest(requestObject); console.log(JSON.stringify(resultObject)); }

推荐答案

您可以通过以下方式使用回调.

You can use callbacks in the following way.

function getRequest(requestObject, callback) { // some code requestToServer({ url : urlInformation, method : 'GET', headers : jsonObject }, function(error, response ,body) { // todo response controlling var responseObject = response.headers; responseObject.body = body; callback(responseObject); }); }

// Controlling the submitted request exports.requestController = function(requestObject) { var method = requestObject['methodInformation']; // Selecting the method if(method == "GET") getRequest(requestObject, function(resultObject){ console.log(JSON.stringify(resultObject)); }); //some code }

希望能有所帮助.

更多推荐

如何等待请求响应并返回值?

本文发布于:2023-06-04 19:12:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/503392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!