简体   繁体   中英

How to asynchronous call function with the result of foreach loop

I have a function that loops over an array of objects and builds an object depending on some parameters. It should return the build object which represents a state object of a component that I will set. However, I would like to use the Array.foreach but I have no idea how to call the function after the foreach loop is done.

The function looks something like this:

 buildStateObject= (someArray: Array) => {
    let stateobject= {};
    someArray.foreach(item => {
      switch (item.Someparameter) {
        case 1:
          stateobject.someProp1= item.message;
          break;
        case 2:
          stateobject.someProp2= item.message;
          break;
        // code omitted
      }

    });
     return stateobject;
  };

and in my component I have something like this which obviously does not work:

if(someJson.jsonArray)
    this.setState(this.buildStateObject(someJson));

So what I am looking for is something like this:


Promise.all(buildStateObject).
  then((theResultObjectMaybe)=>{this.setState(theResultObjectMaybe);})

I tried to figure this out but I was not able to. I am also not sure if this is a good practice todo.

[Edit]

@PaulJanicki thank you for pointing the error out. There were just type errors. However one error you pointed out was also in my code which results in a Unhandled promise rejection and I assumed this was because the forEac h was async and the result was not yet processed.

The problem was a type error foreach instead of the correct forEach

You are missing the return statement outside of the forEach method, in the buildStateObject function. Also forEach should be camelCase.

 function buildStateObject(someArray) { let stateobject = {}; someArray.forEach(item => { switch (item.someparameter) { case 1: stateobject.someProp= item.message; break; case 2: stateobject.someProp= item.message; break; // code omitted } }); return stateobject; } function setState(state) { console.log(state); } var someJson = [{ message: 'first', someparameter: 1 }, { message: 'second', someparameter: 2 }] setState(buildStateObject(someJson))

Also consider that stateobject.someProp will be overwritten with each loop execution, not sure if that's the intended behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM