我正在使用请求模块在NodeJS的“ express post router”内部进行请求。
我可以很好地在请求中获得“价格”值。
但是我想在请求时使用它,例如console.log(price)的位置。
但它说console.log中没有定义价格
如何将其从请求中撤出,以其他方式使用?
exports.clientOrder = async (req, res, next) => {
try {
const { clientID, riderID, clientOrder } = req.body;
await request(
{
method: 'POST',
uri: 'https://api2....',
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
async (error, response) => {
if (error) {
return next(error);
}
const price = Math.imul(totalDistance / 1000, 2000);
},
);
// I want to get price value here out of request.
console.log(price)
return res.send('order finished well');
} catch (error) {
return next(error);
}
};
答案 0 :(得分:1)
await
仅适用于thenable
,您可以将request
动作包装到Promise中,如下所示:
exports.clientOrder = async (req, res, next) => {
try {
const { clientID, riderID, clientOrder } = req.body;
const price = await new Promise((resolve, reject) => {
request(
{
method: 'POST',
uri: 'https://api2....',
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
(error, response) => {
if (error) {
return reject(error);
}
const price = Math.imul(totalDistance / 1000, 2000); // ???
resolve(price);
},
);
});
// I want to get price value here out of request.
console.log(price)
return res.send('order finished well');
} catch (error) {
return next(error);
}
};