如何在调用下一个函数之前等待 firebase.database().ref('users/' + userId).set() 完成?

2024-03-25

我使用以下异步函数将数据写入我的 firebase 实例:

function writeUserData(uid, fn, ln, userEmail) {
  firebase.database().ref('users/' + uid).set({
    firstName: fn,
    lastName: ln, 
    email: userEmail
  });
};

一旦 writeUserData 完成,我想将用户重定向到不同的页面:

window.location.href = "./mypage.html";

据我所知,这可以通过promises https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html但我真的可以用一个很好的例子来理解这个问题。


根据 firebase 文档:https://firebase.google.com/docs/database/web/read-and-write#receive_a_promise https://firebase.google.com/docs/database/web/read-and-write#receive_a_promise, the set方法返回一个承诺。在这种情况下,最简单的例子是:

function writeUserData(uid, fn, ln, userEmail) {
  firebase.database().ref('users/' + uid).set({
    firstName: fn,
    lastName: ln, 
    email: userEmail
  }).then(function onSuccess(res) {
    window.location.href = "./mypage.html";
  }).catch(function onError(err) {
    // do sth, e.g. console.error(err);
  });
};

您的代码和我的示例之间的区别在于我添加的部分:

.then(function onSuccess(res) {
  window.location.href = "./mypage.html";
}).catch(function onError(err) {
  // do sth
});

简而言之,“如果请求成功,则执行onSuccess。如果没有 - 做onError.

您可以在此处获取有关 Promise 如何工作的更多信息:Promise mdn 文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise


为了提高可读性,你可以这样写:

function writeUserData(uid, fn, ln, userEmail) {
  firebase.database().ref('users/' + uid).set({
    firstName: fn,
    lastName: ln, 
    email: userEmail
  })
  .then(onSuccess)
  .catch(onError);
};

function onSuccess(res) {
  window.location.href = "./mypage.html";
}

function onError(err) {
  // do sth
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在调用下一个函数之前等待 firebase.database().ref('users/' + userId).set() 完成? 的相关文章

随机推荐