Home > Enterprise >  Firebase Callable Function can't return after callback
Firebase Callable Function can't return after callback

Time:10-15

I'm new in JS world and callbacks. Why I can't return response after then function for the Firebase callable functions? It returns empty if I return like shown below. I guess it doesn't wait for the response, response has data.output variable actually.

exports.testApi = functions.https.onCall(async(data, context) => {

const formData = new FormData();

formData.append("height", "512");

const response = await axios.post('https://....', formData, {

  headers: formData.getHeaders()
})
.then((response) => {
            
        console.log(response.data);
        return {'imageURL':response.data.output};
          })
          .catch((error) => {
                    console.log(error)
                  });


}
);

It works with this format

const response = await axios.post('https://..', formData, {
  
  headers: formData.getHeaders()
})

return {'imageURL':response.data.output};

CodePudding user response:

The main attraction of async and await is cleaner syntax, in particular syntax that doesn't use then (opinion). You can mix them but I would always try to avoid it, especially here where the task is so simple.

exports.testApi = functions.https.onCall(async(data, context) => {
    try {
        const formData = new FormData();
        formData.append("height", "512");
        
        // Wait for post to give us a response.
        const response = await axios.post('https://....', formData, {
            headers: formData.getHeaders()
        });

        // If we get here, we waited and got a response. Proceed.
        console.log(response.data);
        return {'imageURL': response.data.output}; 
    } catch (error) {
        // If we get here, post threw an error (assuming it throws).
        // And we never executed any lines after const response = await...
        console.log(error);
    }
});

Side note: Firebase Cloud Functions have to be properly terminated and this function does not. For example, if post throws an error and control flows to the catch block then the function will simply timeout because we haven't returned a Promise or thrown a compliant error.

  • Related