未返回Worklight JSONStore结果

时间:2014-05-12 12:54:40

标签: ibm-mobilefirst jsonstore

我有一个函数,如果成功,应该返回JSONStore查询的结果数组。由于某种原因,它不会返回结果。

这是我的功能

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);
});

}

这就是它所在的地方:

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

控制台输出也以奇怪的顺序出现:

 "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

有人知道如何解决它?

1 个答案:

答案 0 :(得分:0)

您似乎期望异步代码同步运行。尝试添加一个回调,一些伪代码:

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));
  });
});