【问题标题】:Why is my promise function returning before finished为什么我的承诺函数在完成之前返回
【发布时间】:2022-01-26 14:16:55
【问题描述】:

在我的标题组件中:

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:

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);
    }
  },
};

读取个人补丁:

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);
  }
},

控制台输出:

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**

在readUserFromFirestore 中,我不确定如何在继续登录过程之前等待将用户的补丁添加到数组中。正在循环的属性之一是profile.patches。 readPersonalPatches() 使用该属性。但在新登录时,readPersonalPatches() 出现错误,因为此时 profile.patches 未定义。 (在缓存后登录时,除了可能已过时的数据之外,我在读取 profile.patches 时没有问题。)

我正在使用 Vue、Vuex 和 Firebase 进行身份验证和 Firestore。 就我而言,补丁和徽章是可互换的术语。

【问题讨论】:

  • 你永远不会等待函数调用(对于异步函数)或返回它返回的承诺(对于非异步函数)。 then 怎么可能知道等待什么?它只是假设整个代码应该是同步的,因为你没有给它任何可以使用的承诺。
  • 非常感谢。我认为then 会继承返回的函数。显然不是。我很感激!
  • async 和 await 几乎没有什么魔力,promise 本身也没有什么魔力。如果您不返回该值,then 肯定无法绕过您传递的函数来尝试找出您要做什么:P await 只是为您返回(每个异步 await本质上是变相的回报,有一点结构将承诺联系在一起)。
  • await (() => { return new Promise((resolve) => { …; resolve(); }); })(); 这件事毫无意义。只需放下包装。

标签: javascript asynchronous async-await promise


【解决方案1】:

感谢 Luaan 让我了解 then 块的工作原理,我现在可以开始了。我没有返回承诺,只是调用函数,然后对返回的承诺不做任何事情?

固定线路:

    .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();
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2019-05-14
    • 1970-01-01
    • 2021-08-15
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多