如何等待“每个数组”功能?

时间:2019-10-11 00:35:33

标签: reactjs express asynchronous synchronous

在函数“ Array.foreach”中,同步/异步系统存在一些问题。 我不知道如何强制代码等待结束。

我尝试使用await / async系统,但是我的代码没有等待“ async responseDB =>”中的代码。

这是我的课程:

...
        let responsesDTO = [];
        await Array.prototype.forEach.call(await searchResponsesByQuestionAndUserId(questions[cpt].idquestion, idUser), async responseDB => {
            if(responseDB !== undefined){
                const responseDTO = {
                    response_id:0,
                    response_text:"",
                    response_type:""
                }
                const responseEntity = await searchResponseByResponseId(responseDB.response_id);
                responseDTO.response_id = responseDB.response_id;
                responseDTO.response_text= responseEntity.text;
                responseDTO.response_type= responseDB.type;
                responsesDTO.push(responseDTO);
            }
        });
        questionResponse.responses=responsesDTO;
        questionResponses[cpt]=questionResponse;
    }

能帮我吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

我不得不模拟您的异步功能。但是,相关的部分是使用for..of而不是forEach

async function searchResponsesByQuestionAndUserId() {
  let responsesDB = [];
  for (let i = 0; i < 10; i++) {
    responsesDB.push({
      response_id: parseInt(1000 * Math.random(), 10),
      type: 'whatever ' + i
    });
  }
  return new Promise((res) => {
    window.setTimeout(() => {
      res(responsesDB);
    }, 1500);
  });

}
async function searchResponseByResponseId(response_id) {
  return new Promise((res) => {
    window.setTimeout(() => {
      res({
        text: 'text for response ' + response_id
      });
    }, 300);
  });
}
async function getResponsesDTO() {
  let responsesDTO = [],
    responsesDB = await searchResponsesByQuestionAndUserId();
  for (let responseDB of responsesDB) {
    if (responseDB === undefined) {
      continue;
    }


    let responseDTO = {
        response_id: 0,
        response_text: "",
        response_type: ""
      },
      responseEntity = await searchResponseByResponseId(responseDB.response_id);
    responseDTO.response_id = responseDB.response_id;
    responseDTO.response_text = responseEntity.text;
    responseDTO.response_type = responseDB.type;
    responsesDTO.push(responseDTO);
    console.log({responseDTO});

  }

  return responsesDTO;
}

getResponsesDTO().then(responsesDTO => {
  console.log(responsesDTO);
});