您好,我正在处理 paypal 函数,但我在 var 中声明了变量,但我不能在函数外使用它,这有问题
async openOrder({request, response }) {
const paypalResponse = await paypal.payment.create(create_payment_json, function(error, payment) {
if (error) {
throw error;
} else {
console.log(payment);
for (let i = 0; i < payment.links.length; i++) {
console.log(payment.links.length);
if (payment.links[i].rel === 'approval_url') {
// I declare varialbe here
var paymentLink = payment.links[i].href;
// response.redirect('payment.links[i].href');
}
}
}
});
console.log(paymentLink) // return undefined
}
我不能使用 response.redirect 的原因是因为我正在处理只返回 json api 的后端 [与前端运行不同的端口] 所以我想在 json 中返回 Link url paypal。
如何在异步函数中声明可变支付链接
最佳答案
好吧,你误解了 javascript 的异步特性。 console.log
甚至会在付款完成之前执行。无论您需要对结果做什么,都应该在回调中给出。
因此,将用户重定向到链接是在回调方法中完成的。我添加了 return
语句,这样就不会发送多个 http 响应。
async openOrder({
request,
response
}) {
const payment = await paypal.payment.create(create_payment_jsonfunction(error, payment) {
if (error) {
throw error;
} else {
console.log(payment);
// do you operations with result here
for (let i = 0; i < payment.links.length; i++) {
console.log(payment.links.length);
if (payment.links[i].rel === 'approval_url') {
// I declare varialbe here
var paymentLink = payment.links[i].href;
return response.redirect('payment.links[i].href');
}
}
}
});
}
关于javascript - 如何在 paypal.payment.create 中声明变量并在外部使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369097/