javascript - fetch:将项目推送到数组

标签 javascript arrays json fetch

我正在努力找出这里出了什么问题。我正在提取一些 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)});
})

关于javascript - fetch:将项目推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572871/

相关文章:

javascript - 通过谷歌表单将内联图像插入自动电子邮件回复

javascript - Bootstrap : How to display 2 tab-contents by clicking on a single tab?

javascript - 在 Android 应用程序上播放 mp3 铃声 - PhoneGap

c++ - 将 ID3D11Texture2D 复制到字节数组,导致内存不足错误 c++

c# - 控制 joopz,可能是 jquery 或 php

javascript - 结合 $(this) 和 $ ("li:eq(ui.item.index())")

java - 从变量创建数组

PHP 通过遍历嵌套树模型构建数组

javascript - jQuery.ajax() 解析器错误

mysql - LimeSurvey 使用数据库中的 JSON 字符串