我正在使用请求模块在 NodeJS 中的“快递路由器”内部进行请求。
我可以很好地在请求中获得“价格”值。
但是我想根据要求使用它,例如 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);
}
};
await
仅适用于 a 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);
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句