与Export一起使用时,请求的响应是未定义的



在一个文件中,我有以下函数来调用外部API并获得一些数据

function RequestCallback(error, response, body) {
if(error) console.log(error);
var new_body = *do something with the body*
console.log(new_body);
return new_body
}
var apiCall = function apiCall(payload, authObj, guest) {
var reqBody = *build the body here*
return request({
url: 'the api url',
method: 'POST',
encoding: null,
headers: {
//pass some headers
},
body: reqBody,
}, RequestCallback);
}
module.exports = {
apiCall: apiCall
};

然后在另一个文件中,我这样称呼它:

const apiService = require("./services.js");
var res = apiService.apiCall(payload, authObj, guest);
console.log(res);

第一个console.log正确打印响应。第二个CCD_ 2打印CCD_。我有一种感觉,这是关于异步调用函数,但我不知道如何在不重写整个部分的情况下解决这个问题。

你很接近。。。您遇到的问题是,您只能访问RequestCallback内部的数据(因为在您的请求完成后,数据将异步返回(。

因此,您在javascript中看到的一种常见模式是传递匿名函数或闭包,作为函数参数,当数据可用时接收数据。这使调用方可以控制对异步返回的数据执行任何操作。

考虑修改apiCall函数以接受callback参数,这样您就可以传入一个函数/闭包,该函数/闭包将在响应返回后对其执行某些操作。

services.js

// note the new function signature takes in a `callback` parameter
var apiCall = function apiCall(payload, authObj, guest, callback) {
var reqBody = *build the body here*
return request(
{
url: "the api url",
method: "POST",
encoding: null,
headers: {
//pass some headers
},
body: reqBody,
},
callback  // the callback is passed here and will get called when the data is ready
);
};
module.exports = {
apiCall: apiCall,
};

现在在您的入口点文件中,我假设它是index.js:

const apiService = require("./services.js");
var res = apiService.apiCall(payload, authObj, guest, function(error, response, body) {
if(error) console.log(error);
var new_body = *do something with the body*
console.log(new_body);
});

现在,无论你想对数据做什么,都需要在回调内部进行。

最新更新