我正在努力看看这里出了什么问题。我正在提取一些 json(是的,我知道我正在使用文本文件)。我在全局范围内有一个数组,我想将条目推送到,我正在遍历 json 并将其推送到该数组。只有当我注销时它是空的。这可能是愚蠢的事情,但任何帮助将不胜感激。
let charities = [];
fetch('../mapdata/markers.txt').then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Network response error.');
})
.then(charData => {
console.log(`inside: ${JSON.stringify(charData, null, 2)}`);
charData.map(entry => {
return charities.push(entry);
});
})
.catch(error => {
console.log('There has been a problem: ', error.message);
});
console.log(`outside: ${JSON.stringify(charities, null, 2)}`);
当它输入时,我认为这可能是一个异步问题......
您正在执行异步操作并在触发异步操作后读取 []。它将永远是空的。
相反,把console.log( outside: ${JSON.stringify(charities, null, 2)}
); 在第二个 then() 内,一旦数据被推入数组。
.then(charData => {
console.log(`inside: ${JSON.stringify(charData, null, 2)}`);
charData.map(entry => {
return charities.push(entry);
});
console.log(outside: ${JSON.stringify(charities, null, 2)});
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句