سؤال

On form load I'm trying to bring back the value of a field not displayed in the form. I haven't used variables like this in SharePoint so please bear with me, most of my calls are done using click functions and promises.

When I use the expression below I get the object back with a bunch of properties and not the boolean value from the field.

var LTE = function() {
    var oList = web.get_lists().getByTitle("Sites");
    var oListItem = oList.getItemById(parentId);
    context.load(oListItem, "LTEActivationComplete");
    context.executeQueryAsync(function() {
        vLTE = oListItem.get_item("LTEActivationComplete");
        return vLTE;
        }, failure)
}
console.log(LTE);

When I call it like below I don't get any value returned to the variable. I can console.log before the return statement and get the correct response...

var LTE = getSiteInfo();
function getSiteInfo(varLTE) {
    var oList = web.get_lists().getByTitle("Sites");
    var oListItem = oList.getItemById(parentId);
    context.load(oListItem, "LTEActivationComplete");
    context.executeQueryAsync(function() {
        vLTE = oListItem.get_item("LTEActivationComplete");
        return vLTE;
    }, failure)
}

Not sure what best practices are for this approach. Is this a case of asynchronization not waiting around for the result?

هل كانت مفيدة؟

المحلول

The problem is that executeQueryAsync is, as the name implies, asynchronous. The return value from your anonymous function is not returned by getSiteInfo, in fact getSiteInfo returns before the anonymous function is called.

The way you normally handle that is by passing in a callback, something like:

getSiteInfo(function(vLTE) {
    // now do something with vLTE
});

function getSiteInfo(callback) {
    var oList = web.get_lists().getByTitle("Sites");
    var oListItem = oList.getItemById(parentId);
    context.load(oListItem, "LTEActivationComplete");
    context.executeQueryAsync(function() {
        vLTE = oListItem.get_item("LTEActivationComplete");
        callback(vLTE); // this passes the value back to the caller
    },  failure)
}

It's basically the same pattern that executeQueryAsync itself uses.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى sharepoint.stackexchange
scroll top