首页 > 解决方案 > 如何在 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。

如何在异步函数中声明我的可变支付链接

标签: javascriptnode.jspaypal

解决方案


好的,您误解了 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');
                }
            }
        }
    });

}

推荐阅读