Как дождаться асин c запроса до фини sh в a для l oop? - PullRequest
1 голос
/ 24 января 2020

Я хочу получить результат асинхронной c функции - в зависимости от результата я либо хочу выполнить другую функцию, либо продолжить для l oop. Вот моя облачная функция:

return query.get().then(geoSnapshot => {
        // If GeoquerySnapshot returns 0 docs, createDoc()
        let docs = geoSnapshot.docs;
        if (docs.length === 0) return createDoc(data);
        for(let [index, doc] of docs.entries()){
            // If age preferences are valid, joinDoc
            let currentDoc = docs[index].data();
            if (validAge(currentDoc, data)){
                let matchedBefore = await(matchedBefore(currentDoc, data))
                if (!matchedBefore){
                    return joinDoc(docs[index], data);
                } else if (index === (docs.length - 1)) {
                    return createDoc(data);
                }
            }
            return
        }
    }).catch( error => {
        console.log("error query: " + error);
        return { error: error };
    })

async function matchedBefore(currentDoc, data){
    return db.collection('users').doc(data.uid).get().then( doc => {
        if ( !doc.exists ) return false;
        // If user1 in matchedUsers
        let matchedUsers = doc.get('matchedUsers');
        if (matchedUsers === undefined) return true
        let matchedBefore = matchedUsers.includes(currentDoc.user1);
        console.log('matchedBefore: ' + matchedBefore);
        if (matchedBefore) { 
            return false 
        } else {
            return true
        }
    })
}

Я получаю следующую ошибку на let matchedBefore = await(matchedBefore(currentDoc, data)):

Each then() should return a value or throw

Как я могу убедиться, что функция matchedBefore() завершается до того, как для l oop продолжается?

1 Ответ

1 голос
/ 24 января 2020

Я думаю, вы слишком запутались с реализацией asyn c -wait. Правильный путь будет:

return query.get().then(async geoSnapshot => {
  // If GeoquerySnapshot returns 0 docs, createDoc()
  let docs = geoSnapshot.docs;
  if (docs.length === 0) return createDoc(data);
  /* eslint-disable no-await-in-loop */
  for(let [index, doc] of docs.entries()) {
    // If age preferences are valid, joinDoc
    let currentDoc = docs[index].data();

    if (validAge(currentDoc, data)){
      let matchedBefore = await(matchedBefore(currentDoc, data))
      if (!matchedBefore){
          return joinDoc(docs[index], data);
      } else if (index === (docs.length - 1)) {
          return createDoc(data);
      }
    }
    return
  }
  /* eslint-enable no-await-in-loop */
}).catch( error => {
    console.log("error query: " + error);
    return { error: error };
})

async function matchedBefore(currentDoc, data){
  let doc = await db.collection('users').doc(data.uid).get()
  
  if ( !doc.exists ) return false;

  // If user1 in matchedUsers
  let matchedUsers = doc.get('matchedUsers');
  if (matchedUsers === undefined) return true

  let matchedBefore = matchedUsers.includes(currentDoc.user1);
  console.log('matchedBefore: ' + matchedBefore);

  return !matchedBefore
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...