【问题标题】:FCF is working but I get this warning: Avoid nesting promises promise/no-nesting [duplicate]FCF 正在工作,但我收到此警告:避免嵌套承诺承诺/不嵌套 [重复]
【发布时间】:2019-03-05 07:19:07
【问题描述】:

我编写了一个 http FCF,它运行两个链接的事务。它有效,但我不知道为什么会收到此警告:

119:16  warning  Avoid nesting promises  promise/no-nesting

这是我写的函数:

exports.checkeaEstadoFinanciero = functions.https.onRequest((req, res) => {
  const body = JSON.parse(req.body);
  const RestoID = body.id;
  const db = admin.firestore();
  const restoRef = db.collection('Restaurantes').doc(RestoID);
  const facturasRef = db.collection('Facturas').where('restaurantID', '==', RestoID);
  return db.runTransaction(transaction => {
    return transaction.get(restoRef).then((restoDoc) => {
      if (restoDoc) {
        if ((restoDoc.data().cicloFacturacion.termino - Date.now()) < 0) {
          //emite una factura
          restoRef.set({ httpPropTest: 'worked fine' }, { merge: true });
        }
      }
      return null;
    })
    .then(() => {
      return db.runTransaction(tran => {
        return tran.get(facturasRef).then(facturasDoc => {
          const holder = [];
          facturasDoc.forEach(doc => {
            holder.push(doc.data());
          })
          console.log('facturas documents', holder);
          return null;
        })
      })
    })
    .catch(err => console.log('error: ', err));
  })
})

我从其他用户那里读到了这个帖子:

Google Cloud Functions - warning Avoid nesting promises promise/no-nesting

我正在做最被接受的答案建议,但我仍然有这个警告。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript google-cloud-functions eslint


    【解决方案1】:

    我的猜测是 ESlint 正在查看您的第二笔交易:

    .then(() => {
      return db.runTransaction(tran => {
        return tran.get(facturasRef).then(facturasDoc => {
          const holder = [];
          ...
        })
      })
    })
    

    并在另一个 then() 回调中抱怨对 then() 的调用。不明白为事务嵌入的 then() 与 first 并没有真正的关系。

    您可以尝试通过将第二个事务移动到一个单独的函数中来向 ESlint 隐藏这个事实,这样它就不会再出现嵌套了:

    .then(() => {
      return secondTransaction()
    })
    
    
    function secondTransaction() {
      return db.runTransaction(tran => {
        return tran.get(facturasRef).then(facturasDoc => {
          const holder = [];
          ...
        })
      })
    }
    

    【讨论】:

    • 我会尝试并回复您。再次感谢道格的快速回答!
    • 它确实奏效了!谢谢。现在代码更简洁易读:D
    猜你喜欢
    • 2019-05-22
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多