我正在尝试构建后端脚本以调用递归api来加载和存储数据。我声明了该函数并将其分配给getAccountInfo,然后尝试调用该函数,但控制台说getAccountInfo不是一个功能。 并且console.log(accountInfo)显示未定义。但是我可以在函数声明中观看它。
api参数需要回调函数,这就是为什么它看起来像这样。
var accountInfo = {};
let getAccountInfo = recurly.accounts.list(function (errResponse, response) {
if (errResponse) {
reject(errResponse);
}
if (response) {
accountInfo = response.data.accounts.account;
resolve(response);
}
}, );
getAccountInfo();
console.log(accountInfo);
我希望我可以运行该功能并获取accountInfo。我是javascript和Node js的新手,是我误解的任何概念吗?非常感谢您的帮助。
答案 0 :(得分:0)
getAccountInfo
是recurly.accounts.list()
返回的结果,它不是一个函数(由于它是一个异步函数,它可能不返回任何内容,也可能返回一个Promise)。您需要自己定义一个函数:
function getAccountInfo() {
recurly.accounts.list(function(errResponse, response) {
if (errResponse) {
reject(errResponse);
}
if (response) {
accountInfo = response.data.accounts.account;
resolve(response);
}
});
}
请注意,您的console.log(accountInfo)
将不会打印结果,因为该函数是异步的。有关构造代码的正确方法,请参见How do I return the response from an asynchronous call?。
答案 1 :(得分:0)
我声明该函数并分配给getAccountInfo
不,那不是您所做的。您调用了函数recurly.accounts.list()并将getAccountInfo设置为其返回的值。由于它是一个异步函数,它可能几乎立即返回,并且很可能它没有返回任何内容,并且getAccountInfo设置为undefined。
此外,在您的代码中未定义拒绝和解决。这就是我的做法,
function getAccountInfo() {
return new Promise((resolve, reject) => {
recurly.accounts.list((errResponse, response) => {
if (errResponse) {
return reject(errResponse);
}
resolve(response);
}, );
});
}
调用getAccountInfo()时,它将返回一个Promise,因此您必须等待它解决。
getAccountInfo()
.then(response => {
accountInfo = response.data.accounts.account;
console.log(accountInfo);
})
.catch(err => console.log(err));