0

I'm really confused about asynchronous functions in general, but I can't seem to return what the api has fetched. Using console.log() gives all the results but I need the function's path (array) for later use.

function callRelation(id) {
    (async () => {
        const api = await fetch(
            "https://www.overpass-api.de/api/interpreter?",
            {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                },
                body: "[out:json];rel(" + id + ");(._;>;);out;",
            },
            
        );


        const request = await api.json();
        let path = [];

        for (let pair of request.elements){
            if (pair.type === "node"){
                path.push([pair.lat, pair.lon]);
            }    
        }
        console.log(path)
        return path;


    })();
}

let test = callRelation(10000);
console.log(test);

I've tried using something called a callback, but I failed miserably at that.

rodd7
  • 53
  • 9
  • This may be helpful to understand more about async, await https://stackoverflow.com/questions/59582780/javascript-async-await-and-fetch-return-the-value-not-the-promise – nerding_it Dec 10 '22 at 12:38

1 Answers1

3

You await to get return from promise function.

async function callRelation(id) {
    const api = await fetch("https://www.overpass-api.de/api/interpreter?", {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
        },
        body: "[out:json];rel(" + id + ");(._;>;);out;",
    });

    const request = await api.json();
    let path = [];

    for (let pair of request.elements) {
        if (pair.type === "node") {
            path.push([pair.lat, pair.lon]);
        }
    }
    console.log(path);
    return path;
}

(async function () {
    let test = await callRelation(10000);
    console.log(test);
})();
Anil kumar
  • 1,216
  • 4
  • 12