简体   繁体   English

如何用foreach循环的结果异步调用function

[英]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.我有一个 function 循环对象数组并根据某些参数构建一个 object。 It should return the build object which represents a state object of a component that I will set.它应该返回构建 object,它代表我将设置的组件的 state object。 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.但是,我想使用Array.foreach但我不知道在 foreach 循环完成后如何调用 function 。

The function looks something like this: function 看起来像这样:

 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. @PaulJanicki 感谢您指出错误。 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.但是,您指出的一个错误也在我的代码中,它导致Unhandled promise rejection ,我认为这是因为forEac h 是异步的,结果尚未处理。

The problem was a type error foreach instead of the correct forEach问题是类型错误foreach而不是正确的forEach

You are missing the return statement outside of the forEach method, in the buildStateObject function.您在buildStateObject function 中缺少 forEach 方法之外的 return 语句。 Also forEach should be camelCase. forEach也应该是 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.还要考虑stateobject.someProp将被每个循环执行覆盖,不确定这是否是预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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