在 Javascript 函数中写入 jQuery 无效

Writing jQuery inside a Javascript function not working

我有一个名为 example.js 的 js 文件,其中有一行如下:

gridOptions.api.setRowData(createRowData());

然后是另一个文件 data.js,它具有应该 return ROW_DATAcreateRowData() 函数。具体如下:

function createRowData() {
    jQuery.getJSON('/file.txt',function(ROW_DATA){

    return ROW_DATA;

    });

}

但是,每当从 example.js 文件中调用此 createRowData() 函数时,它不会进入 jQuery 块内,而只会到达最后一个大括号。谁能告诉我这里出了什么问题?

你从文件中得到JSON,将结果传递给回调函数,然后return它。 Return它在哪里??

正如我所说,您的匿名函数是一个 回调

程序说:当你读完文件后,调用这个函数,好吗?。 当你这样做时,我正在做其他事情。

这就是它的作用。该程序将继续执行,直到文件被读取,此时您的回调匿名函数将被调用。 你可以这样做。

createRowData(gridOptions.api);
// add code here if you want this code to execute even before you get the response
function createRowData(api) {
    jQuery.getJSON('/file.txt',function(ROW_DATA,api){   
    api.setRowData(ROW_DATA);   
    //Whatever else you want to do. In case you want this to be done only 
    //after the values have been read
    });
}

如果你想等待,等待文件被读取,只是,在函数之后不要做任何事情,而是把它放在回调函数中。

我相信您没有得到值,因为 getJSON 是异步的,正如其他人所说的那样。 createRowData 在稍后而不是在调用时检索值。

这是一种通过承诺获取数据的方法。我评论了下面发生的事情:

function createRowData() {
    //return a new promise
    return new Promise(function(resolve, reject){

    jQuery.getJSON('/file.txt',function(ROW_DATA){
     //on reject, send an error
     if (ROW_DATA === null) reject("Error fetching data");
    //on resolve, send the row data
    return resolve(ROW_DATA);

    });
});
}
//use then to describe what happens after the ajax request is done
gridOptions.api.setRowData(createRowData()).then(function(rowdata){
return rowdata; //log data or error
})

编辑:要执行同步 ajax 请求,您可以参考此 SO question 执行类似的操作。

function createRowData() {

    $.ajax({
    url: "/file.txt'",
    async: false,
    success: function(rowdata){
    return rowdata
    }
})

}

要像您提到的那样将一些数据读取到变量,nodejs 可能会有所帮助,因为它可以处理读取 input/output,并且可能还可以读取变量。: