Java 脚本回调不同步

Java script callback not synchronous

我想做什么:

在支付网关服务器中下支付订单并将订单详细信息返回给客户端

使用 firebase 云函数

Order() 执行异步作业,returns function(err,data)

中的订单数据

我试过的:

如您所见,我尝试使用 callback 机制对其进行同步,但似乎无法完成这项工作。仍然返回 null.

index.js代码

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

ippopay_instance.createOrder()中的回调函数可以return一个值,但是调用该函数的代码不会关注return值。

我试着用 promise 包装你的 ippopay_instance.createOrder()

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