如何在节点js中处理这个

how to handle this in node js

目前我正在这样做:

文件名:userOrder.js

const paymentGateway = require('./paymentGateway');

module.exports = {

        save: function() {

            // save user order record  
            return paymentGateway.makePayment();      

        },

        update: function() {

            // update user order record

        }

}

文件名:paymentGateway.js

const payment = require('./payment');

module.exports = {

    makePayment: function() {

        // make payment
        return payment.save();

    }

}

文件名:payment.js

const userOrder = require('./userOrder');

module.exports = {

        save: function() {

            // save payment record
            return userOrder.update();

        }

}

return userOrder.update(); -> 这一行报错“TypeError: userOrder.update is not a function

试试:

module.exports = {

    module.save = function() {

        // save user order record  
        return payment.save();      

    },

    module.update = function() {

        // update user order record

    }

    return module;
}

这是因为您在 payment.jsuserOrder.js 之间使用了循环引用。您可以通过在调用 require 之前为 module.exports 赋值来解决此问题,如下所示:

userOrder.js

const userOrder = function() { };

module.exports = userOrder;

const paymentGateway = require('./paymentGateway');

userOrder.save = function() {
    // save user order record  
    return paymentGateway.makePayment(); 
}

userOrder.update = function() {
    // update user order record
}

payment.js

const payment = function() {};

module.exports = payment;

const userOrder = require('./userOrder');

payment.save = function() {
    // save payment record
    return userOrder.update();
}

不需要对 paymentGateway.js 进行任何更改,因为这不是通告 require 的一部分。