0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Right! Thanks Aleksandr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.