第一次承诺后所有卡住

时间:2019-11-12 19:11:58

标签: javascript node.js promise es6-promise

我有5个Promise.All都在等待执行

GenerateWeekWorkPlan = (.....) => {
    return new Promise(async (resolve, reject) => {

        // Some logic 

        // retVal = ... DB Manipulation ... 

          if (retVal !== null) {             
              resolve({
                status: 200,
                msg: "Successfully created ..."
              });
            } else {              
              reject({
                status: 400,
                msg: "Failed to create ..."
              });
            }

    }

}

const promiseWeek1 = this.GenerateWeekWorkPlan(.....);
const promiseWeek2 = this.GenerateWeekWorkPlan(.....);
const promiseWeek3 = this.GenerateWeekWorkPlan(.....);
const promiseWeek4 = this.GenerateWeekWorkPlan(.....);
const promiseWeek5 = this.GenerateWeekWorkPlan(.....);

Promise.all(
      promiseWeek1,
      promiseWeek2,
      promiseWeek3,
      promiseWeek4,
      promiseWeek5
    )
      .then(success => console.log(success))
      .catch(failed => console.log(failed));

代码仅运行第一个承诺,然后陷入困境。 为什么不继续下一个承诺(2-3-4-5)?

编辑:

GenerateWeekWorkPlan = (weekNumber, packageId, arrayOfTargets) => {
    return new Promise(async (resolve, reject) => {
      // Get all the raw data from Leads collection that is not Duplicated
      console.log("GenerateWeekWorkPlan ...");
      try {
        // 1. Get leads by package id and take all those which are not duplicated
        const leads1 = await Leads.find({
          Duplicate: false,
          PackageId: packageId
        })
          .lean()
          .exec(async (err, leads) => {
            // docs are plain javascript objects instead of model instances



            const oneWeekWorkPlan = arrayOfTargets.map(target => {
              return leads.map(lead => ({
                        .... 
              }));
            });

            console.log("--------Insert Many----------");
            const flatted = oneWeekWorkPlan.flat();
            console.log(flatted);

            const retVal = await WeekPlangs.insertMany(flatted);
            console.log("--------Done Insert Many----------");
            if (retVal !== null) {
              console.log("retVal" + retVal);
              resolve({
                status: 200,
                msg: "Successfully created documents"
              });
            } else {
              console.log("Nothing inside retVal" + retVal);
              reject({
                status: 400,
                msg: "Failed to create documents"
              });
            }
          });
      } catch (err) {
        console.error(err.message);
        reject({
          status: 400,
          msg: "Failed to create documents"
        });
      }
    });
  };
};

1 个答案:

答案 0 :(得分:1)

Never pass an async function as the executor to new Promise!看来您正在使用它,以便可以从异步resolve回调中调用rejectexec()-但实际上您本来不应该使用该回调。您可能想promisify调用并await,或者在MongoDB的情况下,您需要做的就是丢弃回调以重新获得承诺。使GenerateWeekWorkPlan本身成为async函数,以便它返回承诺:

async function GenerateWeekWorkPlan(weekNumber, packageId, arrayOfTargets) {
  // Get all the raw data from Leads collection that is not Duplicated
  console.log("GenerateWeekWorkPlan ...");
  try {
    // 1. Get leads by package id and take all those which are not duplicated
    const leads = await Leads.find({
      Duplicate: false,
      PackageId: packageId
    }).lean();
    // docs are plain javascript objects instead of model instances
    const oneWeekWorkPlan = arrayOfTargets.flatMap(target => {
      return leads.map(lead => ({
        …
      }));
    });

    console.log("--------Insert Many----------");
    console.log(oneWeekWorkPlan);
    const retVal = await WeekPlangs.insertMany(oneWeekWorkPlan);
    console.log("--------Done Insert Many----------");
    if (retVal !== null) {
      console.log("retVal" + retVal);
      return {
        status: 200,
        msg: "Successfully created documents"
      };
    } else {
      console.log("Nothing inside retVal" + retVal);
      throw {
        status: 400,
        msg: "Failed to create documents"
      };
    }
  } catch (err) {
    console.error(err.message);
    throw {
      status: 400,
      msg: "Failed to create documents"
    };
  }
}
相关问题