Javascript 异步函数 - .map - 操作顺序

jos*_*ran 1 javascript async-await

努力使用异步和等待来设置此功能。

我有一个映射对象数组的函数。对于每个对象,我们发出一些外部 axios 请求,在输出更新对象之前接收响应。我需要映射每个对象,更新并返回更新对象的数组。

我遇到的问题是输出没有等待已解决的承诺,导致未定义的值被推送到我的数组中。

我注意到在我们处理每个对象之前,该数组也会被记录。

以下两个函数有问题:

构建对象:

const createHRObj = async function (workflow) {
    if (workflow.type_of_leave === "Personal") {
      getAbsenceDetail(
        `${workflow.employeeID}`,
        `${workflow.startDate}`,
        `${workflow.endDate}`
      ).then((res) => {
        try {
          console.log(`------- Handling Personal Leave! ----------`);
          console.log(workflow);

          if (res.Status != 0)
            throw new Error(`PeopleHR absence status code: ${res.Status}`);

          let absences = res.Result;

          if (absences.length === 0) workflow.on_PeopleHR = false;

          if (absences.length > 0) {
            let count = 0;
            absences.forEach((absence) => {
              if (
                Date.parse(absence.StartDate) <=
                  Date.parse(workflow.startDate) &&
                Date.parse(absence.EndDate) >= Date.parse(workflow.endDate)
              )
                count++;
            });

            count > 0
              ? (workflow.on_PeopleHR = true)
              : (workflow.on_PeopleHR = false);
          }

          console.log(`------- Absence Workflow Output! ----------`);
          console.log(workflow);
          console.log(
            `------- Updating and returning workflow! ----------`
          );
          return workflow;
          // console.log(`------- output from checkedarray ----------`);
          // console.log(checkedArray)
        } catch (err) {
          console.log(err);
        }
      });

      // Else, check for holiday
    } else {
      getHolidayDetail(
        `${workflow.employeeID}`,
        `${workflow.startDate}`,
        `${workflow.endDate}`
      ).then((res) => {
        try {
          console.log(`------- Handling Business Leave! ----------`);
          console.log(workflow);

          if (res.data.Status != 10)
            throw new Error(
              `PeopleHR holiday status code: ${res.data.Status}`
            );

          let holidays = res.data.Result;

          if (holidays.length === 0) workflow.on_PeopleHR = false;

          if (holidays.length > 0) {
            let count = 0;
            holidays.forEach((holiday) => {
              if (
                Date.parse(holiday.StartDate) <=
                  Date.parse(workflow.startDate) &&
                Date.parse(holiday.EndDate) >= Date.parse(workflow.endDate)
              )
                count++;
            });

            count > 0
              ? (workflow.on_PeopleHR = true)
              : (workflow.on_PeopleHR = false);
          }

          console.log(`------- Absence Workflow Output! ----------`);
          console.log(workflow);
          console.log(
            `------- Updating and returning workflow! ----------`
          );
          return workflow;
          // console.log(`------- output from checkedarray ----------`);
          // console.log(checkedArray)
        } catch (err) {
          console.log(err);
        }
      });
    }
  };
Run Code Online (Sandbox Code Playgroud)

第二个函数调用上述函数来处理对象创建,如下所示:

const peopleHR_Check = async function (workflows) {
  console.log(`----- We're now inside the PeopleHR Checker -------`);

  Promise.all(
    workflows.map(async (workflow) => {
      let outputObj = await createHRObj(workflow)
      return outputObj
    })
  )

  .then(res => console.log(res))
};
Run Code Online (Sandbox Code Playgroud)

hev*_*ev1 5

async您需要从函数返回 Promise createHRObj

return getAbsenceDetail(...).then(...)
Run Code Online (Sandbox Code Playgroud)

然而,它使用起来更简单,await因为它是一个async更线性流的函数。

const res = await getAbsenceDetail(...);
// use res (move the code in .then() here)
// return the final output at the end
Run Code Online (Sandbox Code Playgroud)