JavaScript异步函数.then回调返回undefined问题分析与解决
问题:Promise.then回调中获取localID为undefined的原因及解决办法
调用Login函数将用户Google ID与数据库比对,判断是否存在账号,调用代码如下:
Login(DecodedGoogleCredentials.sub).then((localID)=>{//Login returns a promise with the local id for the database console.log(localID);//used to confirm id sessionStorage.setItem("CurrentUserID", localID);//set for refresh setID(localID);//set to recall App setLogin(true);//set to ensure it will be recalled });//end of Login().then(()=>{});
在async函数内部能获取到预期的localID,但在.then回调中执行console.log(localID)时结果为undefined。原Login函数代码如下:
async function Login(GoogleID) {//Called from App() const idQuery = query(idRef, where("id", "==", GoogleID.toString()));//build query for user's id const idDoc = await getDocs(idQuery);//get doc found in query. There should only be one var userFound = false;//user is not found idDoc.forEach((doc) => {//loop through docs userFound = true;//user is found const localID = doc.data().localID; console.log(localID) try { return localID; } catch(e) { console.log(e) } }); //there is no user so far if (userFound==false) {//create new user if user is not found return await CreateUser(GoogleID);//create the login } }//end of Login(id)
此处的console.log(localID)能正常输出预期值,为何.then中会得到不同结果?
问题根源
问题出在forEach循环内的return操作:forEach的回调函数是独立的函数作用域,回调里的return localID只会终止当前回调的执行,并不会把值返回给外层的Login函数。当找到用户时,外层Login函数在forEach执行完毕后没有任何return语句,因此函数默认返回undefined,这就导致.then回调中拿到的localID是undefined。
修正后的代码
async function Login(GoogleID) {//Called from App() const idQuery = query(idRef, where("id", "==", GoogleID.toString()));//build query for user's id const idDoc = await getDocs(idQuery);//get doc found in query. There should only be one var foundDoc; idDoc.forEach((doc) => {//loop through docs foundDoc = doc }); if (foundDoc != null) { const localID = foundDoc.data().localID; return localID; } else {//create new user if user is not found return CreateUser(GoogleID);//create the login } }//end of Login(id)
内容的提问来源于stack exchange,提问作者ACCE
相关产品推荐
相关产品推荐

