我想在嵌套的api调用中使用async await,但不知道怎么做?所以第二个api的响应发送回我从前端得到的\ api \ sign_in响应,这里有什么解决方案是我的代码: ....
app.post("/api/sign_in", (req, res) => {
console.log("i am in login call");
const resp = scaryClown(req.body.email, req.body.password);
console.log("here you should wait for above response and then pass
this response into /api/sign_in response");
res.send(resp);
});
function scaryClown(email, password) {
request.post(
key.sign_in_url,
{
json: {
email: email,
password: password
}
},
function(error, response, body) {
if (!error && response.statusCode == 200) {
email = response.headers.uid;
key.email = response.headers.uid;
key.client = response.headers.client;
var result = [];
for (var i in response.headers) result.push(i, response.headers[i]);
access_token = result[17];
key.access_token = access_token;
key.expiry = response.headers.expiry;
apiresponse = response.body;
console.log("apiresponse");
console.log(apiresponse);
return apiresponse;
}
console.log("==============");
console.log(response.body);
return response.body;
}
);
}
....
答案 0 :(得分:0)
要等待您的ScaryClown函数的响应,可以在使用await之前 您的函数调用。
app.post("/api/sign_in", async (req, res) => {
console.log("i am in login call");
const resp = await scaryClown(req.body.email, req.body.password);
console.log("here you should wait for above response and then pass
this response into / api / sign_in response");
res.send(resp);
});
function scaryClown(email, password) {
return new Promise((resolve, reject) => {
request.post(
key.sign_in_url,
{
json: {
email: email,
password: password
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
email = response.headers.uid;
key.email = response.headers.uid;
key.client = response.headers.client;
var result = [];
for (var i in response.headers) result.push(i, response.headers[i]);
access_token = result[17];
key.access_token = access_token;
key.expiry = response.headers.expiry;
apiresponse = response.body;
console.log("apiresponse");
console.log(apiresponse);
resolve(apiresponse);
}
console.log("==============");
console.log(response.body);
resolve(response.body);
}
);
});
}