Franco Muñiz
Franco Muñiz

Reputation: 921

Wait for Algolia response before returning Cloud Function

I have just implemented algolia in my back-end and I tested it with an http function.

However I now need to use Algolia's search with a callable function. The problem is, it's returning the (null) results before Algolia gives a response (due to being async).

I know I should probably make a promise and wait for algolia to return, but how can I do this? Algolia uses it's own methods and I'm not sure how to implement a promise.

On their documentation there's an example on how to wait for the response, but it only shows it for adding or getting a single object, which is treated differently than a search.

Here's my function:

exports.searchDataInAlgolia = functions.https.onCall((data, context) => {
    var algoliaClient = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_ADMIN_KEY);
    var ALGOLIA_INDEX_NAME = 'users';
    var algoliaIndex = algoliaClient.initIndex(ALGOLIA_INDEX_NAME);

    algoliaIndex.search({
        query: data.textToSearch
    })
        .then(function (responses) {
            return responses.hit;
        });

})

How can I wait for algolia to fetch all the data before returning responses.hit?

This is how I'm calling the cloud function:

searchForUser = (textToSearch) => {

        var searchDataInAlgolia = firebase.functions().httpsCallable('searchDataInAlgolia');
        searchDataInAlgolia({
            textToSearch: textToSearch,
        }).then(function (result) {
            return result.data;
            //Future data manipulation/filtering
        }).then(res => {
            console.log(res);
        })
    }

And I call this function from an onPress on RN passing a string parameter, but that's not the issue for sure.

Upvotes: 1

Views: 280

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600120

You need to return the result of search too:

exports.searchDataInAlgolia = functions.https.onCall((data, context) => {
    var algoliaClient = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_ADMIN_KEY);
    var ALGOLIA_INDEX_NAME = 'users';
    var algoliaIndex = algoliaClient.initIndex(ALGOLIA_INDEX_NAME);

    return algoliaIndex.search({
        query: data.textToSearch
    })
    .then(function (responses) {
        return responses.hit;
    });    
})

Without that the function ends as soon as the last }) is executed, instead of waiting for the results from Algolia to come back (asynchronously).

Upvotes: 0

Related Questions