Search code examples
ibm-mobilefirstjsonstore

Worklight JSONStore result not returned


I have a function which should return the result array of a JSONStore query if it is successful. For some reason it doesn't return the result.

This is my function

function getJSON(){
var collectionName = 'messages';
var query = {title: 'asdf'};
var options =  {
        exact:  false,
        limit:  10
};
result = [];

WL.JSONStore.get(collectionName)
.find(query, options)
.then(function (ArrayResult) {
    result = ArrayResult;
    console.log(result);
    console.log(typeof result);
    return result;
})
.fail(function (errrorObject){
    console.log("could not get JSONStore: \n" + errrorObject);
});

}

and this is where it is called:

$("#button").click( function() {
   console.log("type of returned result in buttonClick: " + typeof getJSON());
})

also the console outputs appear in a weird order:

 "weird orderd output" CDMS_Demo.js:96
 "type of returned result in buttonClick: undefined" CDMS_Demo.html:57
 "result in getJSON: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]" CDMS_Demo.js:89
 "type of result in getJSON: object" CDMS_Demo.js:90

Someone got an idea how to fix it?


Solution

  • You seem to be expecting asynchronous code to behave synchronously. Try adding a callback, some pseudocode:

    function getJSON (callback) {
    
      var collectionName = 'messages';
    
      var query = {title: 'asdf'};
    
      var options =  {
              exact:  false,
              limit:  10
      };
    
      WL.JSONStore.get(collectionName)
    
      .find(query, options)
    
      .then(function (arrayResult) {
          console.log(JSON.stringify(arrayResult));
          callback(arrayResult);
      })
    
      .fail(function (errorObject){
          console.log(errorObject.toString());
      });
    }
    
    $("#button").click(function () {
    
      getJSON(function (arrayResult) {
        console.log(JSON.stringify(arrayResult));
      });
    });