我有一个 json 文件,我正在尝试读取其内容以用于脚本。我正在使用以下方法获取 json:
const json = fetch('Data/my_data.json').then(response => response.json());
当我执行此操作并查看控制台中的 json 对象时,我发现它是一个返回的 promise (已解决状态),其中包含文件中的实际 json 对象。但是您不能直接访问 promisevalue。你必须再次使用 then 语句,所以我使用了这个:
json.then(function(getData){metaData = getData;});
元数据对象未设置为原始 promise 的值。直到第二次完成后,它才会被设置。尽管在最初返回的 promise 中,该信息已经可用。
是否有可能在没有第二个 then 语句的情况下获得原始 promisevalue 或者
我是否使用第二个 then 语句错误地访问了 promise 。
感谢任何见解!
Is it possible to get the original promisevalue without the 2nd then statement or am I accessing the promise incorrectly with the 2nd then statement.
您必须使用 .then()
或 await
从 promise 中获取数据。数据是异步检索的,因此唯一等待它脱离 promise 的是 .then()
或 await
。而且,如果使用 await
,它必须在 async
函数中。
虽然 promises 和 async/await
有助于管理异步操作,但它们无法改变数据是异步检索并且不会同步可用的事实。因此,您必须使用异步工具来获取数据。在这种情况下,它是 .then()
或 await
。
而且,要使用await
,您必须处于支持它的环境中。现代浏览器确实支持它(并且您已经在使用需要半现代浏览器的 fetch()
),但一些仍在使用的旧浏览器并不支持,因此这是一个考虑因素。在这种情况下,您可能应该使用 .then()
。
另请注意,在此编码结构中:
json.then(function(getData){metaData = getData;});
您将 promise 中的数据分配给更高范围变量的地方几乎总是一个警告信号,表明您正试图在您不知道的范围内使用数据数据实际可用和做错事情的时间。
您可以安全使用数据的唯一范围是 INSIDE .then()
处理程序或您从那里调用并将数据传递到的函数。不要将它分配到更高的范围,然后尝试在更高的范围内盲目使用。您不会知道数据何时真正有效。您只知道 .then()
处理程序中的时间信息。
json.then(function(data){
// use the data here
// write the code in here that uses the data
// or call some function here that you pass the data to
processData(data);
});
// can't use the data here (it's not yet available)
有关此问题的进一步说明,请参阅:How do I return the response from an asynchronous call?