简体   繁体   English

无法解决Node.js中的承诺链错误

[英]Not able to resolve promise chain error in Node.js

I have made a function it is actually having many asynchronous calls 我做了一个函数,实际上有很多异步调用

function is something like this 功能是这样的

const createOrUpdatePlan = (billPlans, serviceId, update) => {
  let billPlansWithId;
  let promises = [];
  if (!update) {
    billPlans.map(bp => {
      bp.serviceId = serviceId;
      return bp;
    });
    console.log(billPlans);
    return db.serviceBillPlans.bulkCreate(billPlans);
  } else {

     //first promise
    let findPromise = db.coachingClasses
      .findAll({
        attributes: ['billPlans'],
        where: {
          id: serviceId
        }
      })
      .then(previousBillPlans => {
        //creating new bill plans in edit class
        let newBillPlans = billPlans.filter(bp => !bp.id);

        if (newBillPlans.length > 0) {
          newBillPlans = newBillPlans.map(bp => {
            bp.serviceId = serviceId;
            return bp;
          });
          // console.log(newBillPlans);

           //second promise 
          let createPromise = db.serviceBillPlans
            .bulkCreate(newBillPlans)
            .then(newPlans => {
              let p1;
              billPlansWithId = billPlans.filter(bp => bp.id);
              if (newPlans) {
                newPlans.forEach(element => {
                  let object = {};
                  object.id = element.id;
                  (object.name = element.name),
                    (object.cycle = element.cycle),
                    (object.fees = element.fees);
                  billPlansWithId.push(object);
                });

              }
              console.log(billPlansWithId);
              billPlans = billPlansWithId;
              return billPlans;
            });
          promises.push(createPromise);
        }
      });
    promises.push(findPromise);
    return Promise.all(promises).then((arr) => arr[1] );
  }
};

I am calling this function in another function in which after this function call I am updating the data in another table which is received by this function 我在另一个函数中调用此函数,在该函数调用后,我正在更新该函数接收的另一个表中的数据

Currently what is happening in createOrUpdatePlan function first promise is running but after that in second promise where I am inserting data and after that in then 当前, createOrUpdatePlan函数中的第一个承诺正在发生什么,但是在第二个承诺之后,我正在插入数据, then在那then

 .then(newPlans => {
          let p1;
          billPlansWithId = billPlans.filter(bp => bp.id);
          if (newPlans) {
            newPlans.forEach(element => {
              let object = {};
              object.id = element.id;
              (object.name = element.name),
                (object.cycle = element.cycle),
                (object.fees = element.fees);
              billPlansWithId.push(object);
            });

          }
          console.log(billPlansWithId);
          billPlans = billPlansWithId;
          return billPlans;
        });

This then block code is running after this function has returned data in another function then此功能在其他函数返回的数据块之后代码运行

since I have written console.log in this then block so I am getting logs something like this 因为我已经在中写了console.log then阻止了,所以我正在获取类似这样的日志

INSERT INTO `service_bill_plans` (`id`,`service_id`,`name`,`cycle`,`fees`,`created_at`,`updated_at`) VALUES (NULL,'17','Five Months Plan',5,4000,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP),(NULL,'17','Six Months Plan',6,5000,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP);
undefined
(node:8412) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SequelizeValidationError: notNull Violation: coachingClasses.billPlans cannot be null
(node:8412) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[ { id: 1, name: 'Monthly Plan', cycle: 1, fees: 1000 },
  { id: 2, name: 'Yearly Plan', cycle: 12, fees: 10000 },
  { id: 3, name: 'Two Months Plan', cycle: 2, fees: 1500 },
  { id: 4, name: 'Three Months Plan', cycle: 3, fees: 2500 },
  { id: 5, name: 'Four Months Plan', cycle: 4, fees: 3000 },
  { id: 148, name: 'Five Months Plan', cycle: 5, fees: 4000 },
  { id: 149, name: 'Six Months Plan', cycle: 6, fees: 5000 } ]

Since you can see data is inserted in the table in this function but after that in then block it is not returning before the returning data in this function . 由于您可以看到该函数中的数据已插入表中,但在此之后,则在then块中该数据不会在此函数中返回数据之前返回。

I am really stuck with this promise chain not able to understand what should I do . 我真的迷住了这个诺言链,无法理解我该怎么办。 Please give some hints 请给一些提示

In any promise chain, every then'able block must return a data or a another promise. 在任何承诺链中,每个then'able块都必须返回一个数据或另一个承诺。 This is the thumb rule for a promise chain. 这是承诺链的经验法则。

The function createOrUpdatePlan is returning a promise in "if" block, hence it is expected to return a promise in "else" block also. 函数createOrUpdatePlan在“ if”块中返回一个promise,因此,它也期望在“ else”块中返回一个promise。 It is correct that you are returning Promise.all but you are combining inner promise and outer promise in Promise.all 您返回Promise.all是正确的,但是您在Promise.all中结合了内部承诺和外部承诺

db.coachingClasses    // findPromise is created here (main).
  .findAll({ ... })
  .then(previousBillPlans => {
     // createPromise is created here (inner promise); 

     // This then'able block must have a return data/promise - missing
   })

return Promises.all(); // mix of inner and outer makes no sense.

The expected promise chain is as below 预期的承诺链如下

return db.coachingClasses    // findPromise
  .findAll({ ... })
  .then(previousBillPlans => {
     // return createPromise
   })

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

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