Jap Jap - 3 months ago 9
Ajax Question

Get a JQuery promise using Algolia Instantsearch.js library

I'm using the instantsearch.js library to manage my result from Algolia API.

I would like to know if there is a way to get a promise with instantsearch.js ?

I'm currently using the command :

search.on('render', function() {
// code
});


to execute my code but I would like to wait for other ajax asynchronous results before process my code.

My purpose is to get something like following :

var request1 = $.ajax( url );

var request2 = $.ajax( url );

var result = search.on('render', function() {
// code
}

$.when(request1, request2, result).then(
function(){
console.log("success", arguments);
},
function(){
console.log("fail", arguments);
});


Is anyone have a solution ?

Thanks a lot.

Sam

Answer

Simplest way to promisify the "rendered" event is :

var request1 = $.ajax(url);
var request2 = $.ajax(url);
var rendered = $.Deferred(function(dfrd) {
    search.on('render', dfrd.resolve);
});

$.when(request1, request2, rendered).then(function(result1, result2) {
    console.log(result1, result2);
}, function(error) {
    console.error(error);
});

Although it's not a big deal here, deferreds/promises are rather expensive in terms of performance. You will get the same effect less expensively with :

var request1 = $.ajax(url);
var request2 = $.ajax(url);
search.on('render', function() {
    $.when(request1, request2).then(function(result1, result2) {
        console.log(result1, result2);
    }, function(error) {
        console.error(error);
    });
});
Comments