Home > database >  I can't store response comes from payment api
I can't store response comes from payment api

Time:12-04

ı have been devoloing an e-commerce system but ı have problem with iyzipay payment api. I make successful request and get response from server but I can't store data comes from server. anyone help?

 let returnedData = {}

  iyzipay.payment.create(paymentRequest, function (err, result) {
    if (err) {
      return next(new CustomError("Ödeme başarısız.", 500))
    } 
     return returnedData = result
  })

  //ı can't see data here and return empty {}
  console.log(returnedData)

  // but ı can see here when ı wait 1 second
  setTimeout(() => {
    console.log(returnedData)
  }, 1000);

CodePudding user response:

Since you're calling an async function you should await for it's result. That's why your first console log doesn't print the result and ater 1 sec does, because in that time( the execution time for the stack) you're getting the result

The function that can be awaited:

function createPayment(paymentRequest) {
    return new Promise((resolve, reject) => {
        iyzipay.payment.create(paymentRequest, function (err, result) {
            if (err) reject(new CustomError("Ödeme başarısız.", 500));
            resolve(result);
        });
    });
}

Generally:

(async () => {
    const request = {/* whatever */};
    try {
        const res = await createPayment(request);
        console.log(res); // Now it's here
    } catch(e) { console.error(e); }
})();

You're probably in a route so the actual code would be:

app.use('/payment', async (req, res, next) => {
    try {
        const result = await createPayment(req);
        console.log(result); // Now it's here
        res.end();
    } catch(e) { next(e); }
})

CodePudding user response:

Your first console is getting called before the request gets complete. When waited for 1 sec request is completed and response is stored in the returnData variable. So for your requirement try using promise or call a function to store the response from the create payment function itself with the response as a parameter.

  • Related