在 js 中的回调函数中返回

Return in callback functions in js

本文关键字:函数 返回 回调 js      更新时间:2023-09-26

我正在编写以下函数,我需要返回myJsonString .当我执行函数时,它会异步运行。为了使其同步,我使用了when()then()但它仍然不返回任何内容。

请提出一种方法。

var myJsonString;
var items = [];
function getConfig() {
    $.when(offlinedb.configuration.toArray(function (documents) {
        $.each(documents, function (i, aaa) {
            var obj = {};
            var temp = aaa.Property;
            var tempObj = aaa.Value;
            obj[temp] = tempObj;
            items.push(obj);
        });
        myJsonString = JSON.stringify(items);
    })).then(function (y, yy) {
        console.log(myJsonString);
        // return does not work here..
    });
    return myJsonString;
} 

编辑了我的代码:

var items = [];
var myJsonString;
function getConfig(){
    return offlinedb.configuration.toArray()
   .then(function(documents) {
             $.each(documents,function (i,aaa){
                var obj={};
                var temp=aaa.Property;
                var tempObj= aaa.Value;
                obj[temp]=tempObj;
                items.push(obj);
           });
          myJsonString = JSON.stringify(items);
          return myJsonString;
      });
    }

您无法将异步转换为同步。 您将无法执行以下操作:

var config = getConfig()
function getConfig() {
     // call async functions
     return something;
}

您需要使用承诺,例如

getConfig()
.then(function(config) {
     // you can use config here
})

在 getConfig 函数中,您可以创建一个承诺链:

function getConfig() {
   return offlinedb.configuration.toArray()
   .then(function(documents) {
      // this part is sync
      // process your documents
      return result;
   })
}

看起来$.whenthen是异步的,这意味着您需要处理回调,可能作为函数的参数。 所以例如:

function getConfig(callback){
    $.when(offlinedb.configuration.toArray(function (documents) {
             $.each(documents,function (i,aaa){
                var obj={};
                var temp=aaa.Property;
                var tempObj= aaa.Value;
                obj[temp]=tempObj;
                items.push(obj);
           });
          myJsonString = JSON.stringify(items);
        })).then(function (y,yy){
            callback(myJsonString)
      });
}
// example: getConfig(function(result) { console.log(result); });