我一直试图弄清楚这一点,我没有得到如何将数据返回到另一种方法并调用它以便我不必将数据静态添加到我的请求中。当我运行它来从this.O_Auth返回的数据时,我一直在我的B2C方法上获得未定义的数据。有线索吗?
let obj = {
O_Auth(key, secret) {
const key = Key;
const secret = Secret;
const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");
request(
{
uri: "https://randomurl",
method: 'GET',
headers: {
"Authorization": auth
}
},
(err, res, body) => {
if (err) {
return err;
} else {
// console.log(body);
let response = JSON.parse(body);
let res = JSON.stringify(response.access_token)
return res;
}
}
);
},
B2C(params) {
console.log("Random " + this.O_Auth('first', 'second'));
let options = {
method: 'POST',
uri: 'https://randomurl',
headers: {
"Authorization": "Bearer " + this.O_Auth('first', 'second'),
"Content-Type": "application/json"
},
body: {
//values
},
json: true
};
rp(options)
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err);
});
}
}
答案 0 :(得分:0)
结束搞清楚JavaScript的异步性质意味着我正在请求稍后正在评估的数据,所以我使用了一个承诺来获取数据并在将其输出到随后的承诺输出正文之前将其输出。更改了第一个请求承诺请求(rp),该请求返回第二个方法中该承诺所需的选项。
let obj = {
O_Auth(Key, Secret) {
const key = Key;
const secret = Secret;
const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");
let options = {
uri: "https://randomurl",
headers: {
"Authorization": auth
},
json: true
};
return rp(options)
},
B2C(param1, param2, param3...) {
this.O_Auth('first', 'second'))then(response =>{
let token = response.access_token;
let options = {
method: 'POST',
uri: 'https://randomurl',
headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
},
body: {
//values
},
json: true
};
rp(options)
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err);
});
}).catch(error => console.log(error));
}
}