lisovaccaro
lisovaccaro

Reputation: 33946

How do I make my function return 200 only after asynchronous call has finished?

I developed a CloudFunction using FireBase that upon being called calls an external API, I want my function to return 200 only if the call is succesful, I've been reading about promises however I haven't been able to find out how to do this when using the request library.

How can I return 200 to the caller only when my asynchronous call has finished succesfully?

This is my current code:

exports.payment = functions.https.onRequest((req, res) => {
    var db = admin.firestore();

    if(req.body.action === 'payment.created') {
        const paymentId = req.body.data.id;

        // Get Payment Information from MercadoPago
        request('https://api.mercadopago.com/v1/payments/' + paymentId + '?access_token=' + MP_ACCESS_TOKEN, function (error, response, body) {
            if (!error && response.statusCode === 200) {
                // Return 200 here
            }
        });
    }

    res.send();
});

Upvotes: 0

Views: 445

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

The code to send the response can only be run once you have the result from the third party API. So the res.send() should be inside the request callback:

exports.payment = functions.https.onRequest((req, res) => {
    var db = admin.firestore();

    if(req.body.action === 'payment.created') {
        const paymentId = req.body.data.id;

        // Get Payment Information from MercadoPago
        request('https://api.mercadopago.com/v1/payments/' + paymentId + '?access_token=' + MP_ACCESS_TOKEN, function (error, response, body) {
            if (!error && response.statusCode === 200) {
                res.status(200).send('ok');
            }
        });
    }
});

Upvotes: 2

Related Questions