简体   繁体   English

为什么我的 promise function 在完成之前返回

[英]Why is my promise function returning before finished

In my header component:在我的 header 组件中:

signIn() {
  signInWithPopup(auth, provider).then((result) => {
    this.updateUser(result.user.uid);
    const userRef = doc(db, 'users', result.user.uid);
    this.firestoreUser(userRef)
    .then((userDoc) => {
      if (!userDoc.exists()) {
        this.addNewUserToFirestore(userRef, result.user);
      }
    })
    .then(() => {
      console.log('Read user from firestore');
      // FIXME: readUserFromFirestore still isn't finishing before moving on...
      this.readUserFromFirestore();
    })
    .then(() => {
       console.log('Read personal patches');
       this.readPersonalPatches();
    })
    .then(() => {
      console.log('Add watcher');
      this.geolocationId = navigator.geolocation.watchPosition(
        this.nearLandmark,
        this.errorCallback
      );
    });
  });
},

readUserFromFirestore:读取UserFromFirestore:

async readUserFromFirestore({ commit, state }) {
    const userRef = doc(db, 'users', state.user);
    try {
      const userDoc = await getDoc(userRef);

      await (() => {
        return new Promise((resolve) => {
          for (const property in userDoc.data()) {
            const propertyValue = userDoc.data()[property];
            commit('addProfileProperty', {
              propertyName: property,
              propertyValue,
            });
          }
          console.log(
            'Just finished putting in user patches',
            state.profile.patches
          );
          resolve();
        });
      })();
    } catch (e) {
      alert('Error!');
      console.error(e);
    }
  },
};

readPersonalPatches:阅读个人补丁:

async readPersonalPatches({ commit, state }) {
  try {
    if (state.user) {
      // Get a copy of all the user's patches
      state.ownedPatchesArray = [];
      state.unownedPatchesArray = [];
      await (function () {
        console.log('Made it inside the await from readpersonalpatches');
        return new Promise((resolve) => {
          console.log('raw badges', state.rawPatches);
          console.log('user badges', state.profile.patches);
          state.rawPatches.forEach((patch) => {
            if (JSON.stringify(state.profile.patches).includes(patch.slug)) {
              commit('addToArray', {
                arr: 'ownedPatchesArray',
                value: patch,
              });
            } else {
              commit('addToArray', {
                arr: 'unownedPatchesArray',
                value: patch,
              });
            }
          });

          resolve();
        });
      })();
    }
  } catch (error) {
    alert('Error reading personal patches');
    console.log(error);
  }
},

Console Output:控制台 Output:

Read user from firestore
Read personal patches
Made it inside the await from readpersonalpatches
raw badges **accurate badge list**
user badges undefined
TypeError: Cannot read properties of undefined (reading 'includes')
Add watcher
Just finished putting in user patches **accurate user patch list**

In readUserFromFirestore I wasn't sure exactly how to approach waiting on the user's patches to be added to the array before moving on in the sign-in process.readUserFromFirestore ,我不确定如何在继续登录过程之前等待将用户的补丁添加到数组中。 One of the properties that is being looped over is profile.patches .正在循环的属性之一是profile.patches readPersonalPatches() uses that property. readPersonalPatches()使用该属性。 But on fresh logins I get an error in readPersonalPatches() because profile.patches is undefined at that point.但是在新登录时,我在readPersonalPatches()中收到错误,因为此时profile.patches是未定义的。 (On logins after cacheing I do not have an issue reading profile.patches apart from the data potentially being outdated.) (在缓存后登录时,除了可能已过时的数据之外,我在读取 profile.patches 时没有问题。)

I am using Vue, Vuex, and Firebase for Authentication and Firestore.我正在使用 Vue、Vuex 和 Firebase 进行身份验证和 Firestore。 For my purposes patch and badge are interchangeable terms.就我而言,补丁和徽章是可互换的术语。

Thanks to Luaan for educating me on how then blocks work I have it going now.感谢 Luaan 向我介绍then块如何工作,我现在已经开始了。 I wasn't returning the promises, only calling the function and then not doing anything with the returned promises我没有返回承诺,只调用 function 然后对返回的承诺不做任何事情

Fixed lines:固定线路:

    .then((userDoc) => {
      return (function () {
        if (!userDoc.exists()) {
          this.addNewUserToFirestore(userRef, result.user);
        }
      })();
    })
    .then(() => {
      console.log('Read user from firestore');      
      return this.readUserFromFirestore();
    })
    .then(() => {
       console.log('Read personal patches');
       return this.readPersonalPatches();
    })

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

相关问题 异步函数不返回完成的承诺 - Async function not returning finished promise 为什么我的react / redux函数没有返回承诺? - Why is my react/redux function not returning a promise? 然后.then()函数似乎在promise完成之前运行 - Then .then() function seems to run before the promise is finished 如何在从我的 promise / function 返回之前等待 forEach 完成 - How to wait for a forEach to finish before returning from my promise / function 为什么我的函数从我的数据库返回一个承诺而不是一个对象? - Why is my function returning a promise and not an object from my db? 为什么我的 function 返回 Promise {<pending> } 而不是我的条目?</pending> - Why is my function returning a Promise { <pending> } instead of my entries? 为什么我的函数在我的 Promise 回调之前执行? - Why does my function execute before my promise callback? 为什么我的异步 function 返回 Promise {<pending> } 而不是一个值?</pending> - Why is my asynchronous function returning Promise { <pending> } instead of a value? 为什么我的异步函数在等待后返回一个挂起的承诺? - Why is my async function returning a pending promise after await? 为什么我的 map function 在 promise 中使用时返回未定义? - Why is my map function returning undefined when used within a promise?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM