Hiren Makwana Hiren Makwana - 4 days ago 3
Node.js Question

how to handle this in node js

Currently I'm doing this:

filename : userOrder.js

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

module.exports = {

save: function() {

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

},

update: function() {

// update user order record

}

}


filename: paymentGateway.js

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

module.exports = {

makePayment: function() {

// make payment
return payment.save();

}

}


filename : payment.js

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

module.exports = {

save: function() {

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

}

}


return userOrder.update(); -> this line gives an error "TypeError: userOrder.update is not a function"

dan dan
Answer

This is because you are using circular references between payment.js and userOrder.js. You can fix this by assigning a value to module.exports before you call require, like this:

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();
}

No changes are required to paymentGateway.js, as this isn't part of a circular require.