问题描述
我想将body的内容保存到全局变量returnData
中,以便可以将其返回给外部函数。但是,只有当我在回调中console.log
时,它才起作用。数据不会保存到全局变量中。
var returnData; // This is where I want to store the output of request.post
function getDataFromPostRequest() {
request.post(
{
url: "http://example.com",formData: {x: "y"},},function optionalCallback(err,httpResponse,body) {
console.log(body) // this is working
returnData = body;
}
);
}
console.log("returnData ",returnData); // This is undefined
解决方法
也许您可以做到:
var returnData; // This is where I want to store the output of request.post
function getDataFromPostRequest() {
request.post(
{
url: "http://example.com",formData: {x: "y"},},function optionalCallback(err,httpResponse,body) {
console.log(body) // this is working
returnData = body;
console.log("returnData ",returnData);
}
)
}