DevJZ
DevJZ

Reputation: 100

Firebase http function finishing before http request library returns data

I have an HTTP triggered Firebase function, which uses the request library https://github.com/request/request to make an HTTP post to another API. The logs show the POST request is returning the correct data but the Firebase function is finishing before the Async POST returns the data. How do I make the overall function wait for the POST request?

const functions = require('firebase-functions');
var requestDependency = require('request');

exports.XXXXXXXXXX = functions.https.onRequest((request, response) => {

    var answer = 'testo';
    var jsonResponse = null;
    var jsonData = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    let url = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //or production  

    requestDependency.post({

        headers: {    
            'content-type': 'XXXXXXXXXXXXXXXXXXXX'  ,
            'Accept': 'XXXXXXXXXXXXXXXXXXXX',
            'XXXXXXXXXX-Access-Token': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
        },

        url: url,  
        body: jsonData 

    }, function(error, response, body) { 

        if (error) {  
            console.log('errrrrrrrror1')
        } else {
            jsonResponse = body;
            console.log(jsonResponse); <-----Shows correct data returned
            console.log('Done.');
            answer = jsonResponse;
            console.log('TEST: ' + answer)
        }
    });

    console.log("Performing search");
    response.send(cardName+" "+jsonResponse); <---jsonResponse not populated
});

Upvotes: 1

Views: 442

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

According to the documentation, HTTP functions are terminated when a response is sent to the client. This means your call to response.send() is effectively terminating the function.

The problem is that the call to post() is asynchronous and returns immediately while the HTTP request continues in the background. Function execution continues right after the post. This means your sent response is almost certainly going to get executed before the HTTP request finishes.

If you want to wait for the HTTP request to finish, put your response to the client inside the callback that handles the response from the HTTP request.

function(error, response, body) { 
    if (error) {  
        console.log('errrrrrrrror1')
        // send an error response here
    } else {
        jsonResponse = body;
        console.log(jsonResponse); <-----Shows correct data returned
        console.log('Done.');
        answer = jsonResponse;
        console.log('TEST: ' + answer)
        // send an success response here
    }
});

Also watch this video series to get a better grasp on how Cloud Functions works: https://www.youtube.com/watch?v=7IkUgCLr5oA&index=2&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM

Upvotes: 2

Related Questions