JavaScript Asyn c с методом pu sh () - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь получить объект JSON из API и преобразовать его в Geo JSON, используя блок кода, который я нашел в Интернете. Так как я решил использовать Fetch API, меня перетащили в кроличью нору Asynchronous JavaScript, к которой я не готов или, возможно, не достаточно умен, чтобы справиться с ним!

При запуске нижеприведенного я получаю:

Невозможно прочитать свойства 'sites' undefined

Я думаю, потому что эта часть моего кода не асинхронна. Однако я не знаю, как исправить, но очень хотел бы попытаться понять. Пожалуйста?

const fetch = require('node-fetch');

async function fetchSites() {
    const response = await fetch('http://webtris.highwaysengland.co.uk/api/v1.0/sites');
    const sitesJSON = await response.json();
    return sitesJSON;
}

async function sitestoGeoJSON() {
    const sitesJSON = await fetchSites();
    //console.log(sitesJSON);
    console.log(sitesJSON.sites[0].Id);
    console.log(sitesJSON.sites[1].Id);
    console.log(sitesJSON.sites[0].Longitude);
    console.log(sitesJSON.sites[1].Longitude);

    var sitesGeoJSON = {
        type: "Feature Collection",
        features: []
    };

    sitesGeoJSON.features.push({
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates": [sitesJSON.sites[0].Longitude, sitesJSON.sites[0].Latitude]
        },
        "properties": {
            "Id": sitesJSON.sites[0].Id,
            "Name": sitesJSON.sites[0].Name,
            "Description": sitesJSON[0].sites.Description,
            "Status": sitesJSON[0].sites.Status
        }
    });

    /* for (i = 0; i < sitesJSON.sites.length; i++) {
        sitesGeoJSON.features.push({
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [sitesJSON.sites[i].longitude, sitesJSON.sites[i].latitude]
            },
            "properties": {
                "Id": sitesJSON.sites[i].Id,
                "Name": sitesJSON.sites[i].Name,
                "Description": sitesJSON[i].sites.Description,
                "Status": sitesJSON[i].sites.Status,
            }
        });
    } */

    return sitesGeoJSON
}

/* fetchSites()
    .then(sitesJSON => console.log(sitesJSON))
    .catch(reason => console.log(reason.message)) */

sitestoGeoJSON()
    .then(sitesGeoJSON => console.log(sitesGeoJSON))
    .catch(reason => console.log(reason.message))

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...