Search code examples
javascriptjqueryajaxsummernote

jQuery promises with summernote hints


I am working on getting a live user list from a database for the Summernote Hints however when using async it just falls over, however with async off it causes the UI to freeze... clearly not optimal for the UX.

$(document).ready(function()
{
    $('.editor').summernote({
        height: 300,
        hint: {
            match: /\B@(\w*)$/,
            users: function(keyword) {

                var result = data;

                $.ajax({
                    url: '/users/' + keyword,
                    type: 'get',
                    async: false //This works but freezes the UI
                }).done(function(data)
                {
                    result = data; //Set the result to the returned json array
                });

                return result;
            },
            search: function (keyword, callback) {
                callback(this.users(keyword)); //callback must be an array
            },
            content: function (item) {
                return '@' + item;
            }
        }
    });
});

How can I get async to work without falling over? I believe it has something to do with promises however not sure.


Solution

  • Don't call callback. users needs to call that from the done function.

    $(document).ready(function()
    {
        $('.editor').summernote({
            height: 300,
            hint: {
                match: /\B@(\w*)$/,
                users: function(keyword, callback) {
                    $.ajax({
                        url: '/users/' + keyword,
                        type: 'get',
                        async: true //This works but freezes the UI
                    }).done(callback);
                },
                search: function (keyword, callback) {
                    this.users(keyword, callback); //callback must be an array
                },
                content: function (item) {
                    return '@' + item;
                }
            }
        });
    });