Search code examples
javascriptnode.jsfirebasegoogle-cloud-functionsasynccallback

Java script callback not synchronous


What am trying to to do :

Placing a payment-order in payment gateway server and returning order details back to client

using firebase cloud functions

the Order() does the asynchronous job and returns the order's data in function(err,data)

What I tried :

as you can see I tried to synchronize it using callback mechanism which doesn't seem to do the job. Still returning null.

index.js code

  const functions = require("firebase-functions");

 


/* eslint-disable */
exports.order = functions.https.onCall((amnt, context) => {
    
    var orderdata;
    const Ippopay = require('node-ippopay');
    var ippopay_instance = new Ippopay({
        public_key: 'pk_live_0WZhCNC5l7PJ',
        secret_key: 'secret ;) ',
      });
      
    function Order(callback){
     ippopay_instance.createOrder({
          amount: amnt,
          currency: 'DOLLAR',
          payment_modes: "cc,dc,nb",
          customer: {
              name: "Test",
              email: "test@gmail.com",
              phone: {
                  country_code: "63",
                  national_number: "5876543210"
              }
          }
      },

          function (err, data) {

            orderdata=data;
          });    
          callback(orderdata);
    }
    return Order(function(order) {
        //response.send(order);
        return orderdata;
    });   
});

Solution

  • A callback function inside ippopay_instance.createOrder() can return a value, but the code that calls the function won't pay attention to the return value.

    I try to wrap your ippopay_instance.createOrder() in promise instead.

    const functions = require("firebase-functions");
    
    /* eslint-disable */
    exports.order = functions.https.onCall((amnt, context) => {
      const Ippopay = require("node-ippopay");
      const ippopay_instance = new Ippopay({
        public_key: "pk_live_0WZhCNC5l7PJ",
        secret_key: "secret ;) ",
      });
      const param = {
        amount: amnt,
        currency: "DOLLAR",
        payment_modes: "cc,dc,nb",
        customer: {
          name: "Test",
          email: "test@gmail.com",
          phone: {
            country_code: "63",
            national_number: "5876543210",
          },
        },
      };
    
      function getStuffAsync(param) {
        return new Promise(function (resolve, reject) {
          ippopay_instance.createOrder(param, function (err, data) {
            if (err !== null) reject(err);
            else resolve(data);
          });
        });
      }
    
      return getStuffAsync(param);
    });