简体   繁体   English

JSON.Parse()准备好时调用函数吗?

[英]Call function when JSON.Parse() is ready?

当JSON.Parse()已解析文件中的所有对象时,是否可以使用事件来调用函数?

JSON.parse is synchronous. JSON.parse是同步的。 it returns the object corresponding to the given JSON text. 它返回与给定JSON文本对应的对象。

More about it from mozilla 来自mozilla的更多信息

now a good way of doing JSON.parse is shown below (inside a try-catch) 现在下面显示了一种执行JSON.parse的好方法(在try-catch中)

try {
    var data = JSON.parse(string);
    //data is the object,
    //convert to object is completed here. you can call a function here passing created object                  
}
catch (err) {
    //mark this error ?
}

Now there are discussions, about why JSON.parse is not async, like the ONE HERE 现在讨论,为什么JSON.parse不异步,例如ONE HERE

EDIT: Since question was changed. 编辑:由于问题已更改。

JSON.parse() is a synchronous method, meaning that once it's called it will execute fully, before code execution continues. JSON.parse()是一个同步方法,这意味着一旦调用它,它将在代码执行继续之前完全执行。

var obj= JSON.parse(jsonString);
obj.prop; // obj is already accessible.

JSON.parse, doesn't actually load any files. JSON.parse,实际上不加载任何文件。 It's also synchronous, meaning that code execution resume, after it has finished it's function, which is to parse a valid JSON string, to a JavaScript object. 它也是同步的,这意味着代码执行完成后,它的功能(将有效的JSON字符串解析为JavaScript对象)将恢复执行。

If you want to execute a callback after a file has loaded, you'd need to look into requests, and ajax to be more precise. 如果要在文件加载后执行回调,则需要调查请求和ajax,以便更加精确。 Here's a simple example using jQuery. 这是一个使用jQuery的简单示例。

$.ajax({
  url: 'url/to/file.json',
  dataType: 'json'
}).done(yourCallback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM