codex
codex

Reputation: 87

Interference in data retrieval

I have three functions as shown:

async doAction (link, state)
  {
    try {
      let response = await fetch(
        'http://xxx.tld/'+link,
        {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          type:1
        })
      }, {timeout: 500});

      let responseJson = await response.json();

      alert(state)

      switch (state) {
        //somethings
        .
        .
        .
        default:

      }

    } catch (error) {
      //alert(error);
    }    
  }

  async componentDidMount(){
    this.doAction('loadModAdv.php', 1)
  }

  async loadModAdv(object){
     object.map(async (data)=>{
      if(data.status == "1")
      {

        await this.doAction(data.fileName, parseInt(data.moduleAdvertise, 10) + 1)
      }
    })
  }

When "await this.doAction" is executed in the map, the "alert(state)" does not return the data in sequence.

Sometimes 1 2 4 and sometimes 1 4 2

What is the solution?

Upvotes: 1

Views: 32

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30370

To achieve consistent/deterministic asynchronous iteration over an array, consider updating your code to use the following pattern:

async loadModAdv(object){
    for(const data of object) {
        if(data.status == "1") {
            await this.doAction(data.fileName, parseInt(data.moduleAdvertise, 10) + 1)
        }
    }
}

As a note, I noticed you used the map function to iterate however it didn't seem that you're using the result of the map, so in this answer I've opted for a simpler solution based on a for loop.

If you wanted to achieve "map-like" behaviour via this pattern, you could do something like this:

async loadModAdv(object){

    var results = []

    for(const data of object) {
        if(data.status == "1") {
            results.push(await this.doAction(data.fileName, parseInt(data.moduleAdvertise, 10) + 1))
        }
    }

    console.log('data in order ', JSON.stringify(results))
}

Hope that helps!

Upvotes: 1

Related Questions