如果循环中出现打字稿错误

时间:2019-05-27 14:27:31

标签: javascript typescript

我具有应该从用户那里获得推荐代码的功能。用户提供一个代码,并检查引用代码是否存在于数据库中,然后评估

  1. 它与当前用户不匹配,因此不应引用自己,并且

  2. 它与数据库中的代码之一匹配

但是,即使给出的代码在数据库中,此代码也找不到匹配项。如果引荐代码与当前用户之一匹配,则它可以正常工作并指出,即一个人不能引荐自己。

但是,如果引荐代码与另一个用户的匹配(即引荐系统应如何工作)相匹配,它仍会说没有匹配项。

如何清除此错误

export const getID = functions.https.onCall(async(data, context) => {
  const db = admin.firestore();
  const usersSnapshot = await db.collection("user").get();
  const allUIDs = usersSnapshot.docs.map(doc => doc.data().userID);

  const userID = context.auth.uid;
  const providedID = "cNx7IuY6rZlR9mYSfb1hY7ROFY2";


 //db.collection("user").doc(providedID).collection("referrals").doc(userID);

  await check();

  function check() {
    let result;
    allUIDs.forEach(idFromDb => {
      if (providedID === idFromDb && (idFromDb === userID)) {
        result = "ownmatch";
      } else if (providedID === idFromDb && (idFromDb !== userID)) {
        result = "match";
      } else {
        result = "nomatch";
      }
    });
    return result;
  }

  if (check() === "match") {
    return {
      message: `Match Found`,
    };
  } else if (check() === "ownmatch") {
    return {
      message: `Sorry, you can't use your own invite code`,
    };
  } else {
    return {
      message: `No User with that ID`
    };
  }
});

1 个答案:

答案 0 :(得分:0)

(这不是答案,而是一个简单的重构。)

这是您的代码当前正在执行的操作(大约我没有运行它):

const resultMsgs = {
  nomatch:  'No User With That ID',
  ownmatch: 'Sorry, you can\'t use your own invite code',
  match:    'Match Found',
}

function check(uids, providedId, userId) {
  let result

  uids.forEach(idFromDb => {
    if (providedId !== idFromDb) {
      result = 'nomatch'
      return
    }

    if (userID === idFromDb) {
      result = 'ownmatch'
      return
    }

    result = 'match'
  })

  return result
}

export const getID = functions
  .https
  .onCall(async (data, context) => {
    const userId     = context.auth.uid
    const providedId = 'cNx7IuY6rZlR9mYSfb1hY7ROFY2'

    const db   = admin.firestore()
    const user = await db.collection('user').get()
    const uids = user.docs.map(doc => doc.data().userId)

    const checkResult = check(uids, providedId, userId)
    return { message: resultMsgs[checkResult] }
  })

(我删除了看似虚假的数据库收集操作。)

您的forEach遍历了所有uuids,但是result将被设置为上一次比较的结果。也许这是正确的,但是:

  • 如果您要查找任何匹配项,那不是您想要的。
  • 如果您要查找所有匹配项,那不是您想要的。
  • 如果您要匹配 last UUID,这就是您想要的,但这是一种奇怪的解决方法。

所以:

  • 如果要匹配任何,请使用... ahem 任何形式的any函数。
  • 如果要所有匹配,请使用任何形式的all函数。
  • 如果要先匹配 ,则只需检查第一个元素即可。
  • 如果您想要完整的比较集 ,则需要使用map而不是forEach,并适当地处理每个结果,无论您的情况如何。

无论如何,我建议您更清晰地分解代码。进行推理和修复会容易得多。