Iñigo
Iñigo

Reputation: 2016

Angular - Wait function before continue executing?

I have an angular function similar to the following. There is a loop where every time I do a POST request and concat the respose in a variable:

async loop(jsonData){
    var text: any;
    for(var i=0; i<jsonData.Hoja1.length; i++){
        var id = jsonData.Hoja1[i].id.toString();
        var codigo = Number(jsonData.Hoja1[i].codigo).toString();
        var featureRequest = new WFS().writeGetFeature();
        fetch('http://localhost:3000/inspire', {
            method: 'POST',
            body: new XMLSerializer().serializeToString(featureRequest)
        }).then((response) => {
            return response.json();
        }).then((json) => {
            var features = new GeoJSON().readFeatures(json);
            if(features[0]){
                var format = new WKT();
                var wktRepresenation  = format.writeGeometry(features[0].getGeometry());
                var consulta = "UPDATE " + wktRepresenation + ";";
                text = text + consulta;
            }
        });
    }
    return text;
}

I'm trying to print the function result but it returns an undefined value.

this.loop(jsonData).then( res => {console.log(res)});

It seems that .then does not wait till loop function ends its execution, or I am doing something wrong inside the loop function (Maybe the POST call?).

Please guide me, I'm pretty nobbie on sychronization. How can I get the correct value? Thanks.

Upvotes: 0

Views: 382

Answers (1)

Aleksandr Yatsenko
Aleksandr Yatsenko

Reputation: 869

Write await before fetch. await fetch('http://localhost:3000/inspire', ... Because you must wait completed fetch in each iteration of loop.

Upvotes: 1

Related Questions