0

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?

1

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.

  • Thanks for this! Huge help! I'm still trying to figure out how to get the result outside of the calling function (getSiteInfo) though... – Ghoztrider Mar 4 at 19:45
  • I think you're struggling because your trying to treat asynchronous code as if it's synchronous. What you're calling 'outside of the calling function' has already run to completion and exited by the time your asynchronous callback get's called. Whatever work you need to do with vLTE, your only option is to do it inside the callback, which get's passed vLTE. – Joe McShea Mar 4 at 20:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.