Domanda

I would like to make use of the jQuery $.Deferred/promise functionality together with the SharePoint JavaScript API. Here is an example of what I am trying to achieve.

function getCachedSearches() {
    var dfd = $.Deferred(function () {
        var list = context
                .get_web()
                .get_lists()
                .getByTitle('CachedSearches');

        cached_searches = list.getItems('');

        context.load(cached_searches);

        context.executeQueryAsync(
           function () {
               dfd.resolve();
           },
           function (sender, args) {
               dfd.reject(args.get_message());
           }
        );
    });
    return dfd.promise();
}

function addCachedSearch(phrase) {
    var dfd = $.Deferred(function () {
        var list = context
                .get_web()
                .get_lists()
                .getByTitle('CachedSearches');

        var create_item = new SP.ListItemCreationInformation();
        var list_item = list.addItem(create_item);

        list_item.set_item('Title', phrase);

        list_item.update();

        context.load(list_item);

        context.executeQueryAsync(
           function () {
               dfd.resolve();
           },
           function (sender, args) {
               dfd.reject(args.get_message());
           }
        );
    });
    return dfd.promise();
}

function doSearch() {
    addCachedSearch($('#phrase').val())
        .then(getCachedSearches());
}

Unfortunately the above code does not work as expected - the second call does not wait for the first promise to be resolved before executing. Many thanks

È stato utile?

Soluzione

I think I see a problem: .then() expects a function reference, but you're invoking the function and passing-in the result (in this case, a Promise). Try this instead:

function doSearch() {
    addCachedSearch($('#phrase').val())
        .then(getCachedSearches);
}

Note that getCachedSearches no longer has the () parens.

Just for kicks, here's a jsFiddle with a distilled example of what it appears you're trying to do: http://jsfiddle.net/UbBz3/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top