Convert fetch API code to ".then" notation code

How can I covert following code into .then notation. I want to use strictly use “.then” notation. That is what I observed with my system.

var obj = [{"Id":"10101","descr":"server1.com"},{"Id":"10102","descr":"server2.com"},{"Id":"10103","descr":"server3.com"},{"Id":"10104","descr":"server4.com"},{"Id":"10105","descr":"server5.com"},{"Id":"10106","descr":"server6.com"},{"Id":"10107","descr":"server7.com"}];
var temp = [];
for (var i = 0; i < obj.length; i++){     
var id = obj[i].Id;
    let response = await fetch('https://abced.com/api/'+id+'/value', {method : "GET", headers: {"Authorization": "xyz"}});
    var data = await response.json();
    var stats = data.status; 
        if (stat != "OK")
                {
                    temp.push({Id:obj[i].Id, descr:obj[i].descr, value:"ERROR"})
                }       
    }
console.log(temp);

My expected output is, (values of Id and descr will depends on “if statement” in the code)

[{"Id": "10101","descr": "server1.com","status": "ERROR"},
{"Id": "10103","descr": "server3.com","status": "ERROR"},
{"Id": "10104","descr": "server4.com","status": "ERROR"}]

Can someone please help here.

MDN has an example of how to use fetch with then (it’s the first code example on the page).

MDN: Using the Fetch API

@camperextraordinaire, my system doesn’t allow me to use it. In details, await not actually waiting for output to return hence code is failing.

I’m utilizing JavaScript event of Dynatrace APM tool (synthetic module). I divided entire logic into three steps. These three steps will have individual JavaScript events. For 1st and 3rd step, I have code ready which is working smoothly. However, the one I mentioned above is 2nd and for which I’m struggling to get required output.
Adding 1st step code here,

fetch('https://getserver.com/api').then((res) => res.json()).then(function(data) {     var value = data.values;     const formatData = (temp) => {         return temp.map(({             Id, value: {descr}}) => ({Id, descr})); };     var output = formatData(value);     console.log(output) }).catch(e => {    console.log("fetch fail: " + e);});

This issue is sorted. Thanks for the suggestions and support

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.