javascript - 如何在 paypal.paypent.create 中声明变量并在外部使用
问题描述
嗨,我正在研究 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 [run different port with frontend] 的后端,所以我想在 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');
}
}
}
});
}
推荐阅读
- swift - 如何排队大量入站 CloudKit 通知
- java - 如何在 JFrame 上显示 Graphics2D 对象
- java - 用于抛出异常的内联 lambda 语法
- javascript - 过滤html表格(JS)
- scala - 对于理解返回类型
- django - 使用 Django-rest-auth 创建新用户时创建自定义用户模型
- java - 使用函数为 Get 和 Post 请求创建通用类的最简单方法?
- javascript - 使用 jmeter 在 selenium 中执行 java 脚本时方法调用出错
- python - 如何在 Ubuntu 17.10 上为 anaconda 创建桌面条目?
- javascript - 时刻列中的触发函数在GridX中排序