如何从javascript中的函数返回值,这涉及异步调用

时间:2017-12-30 03:03:14

标签: javascript node.js asynchronous

  

我在服务器端使用nodejs进行了一些cookie验证。每当我收到get URL请求时,我都会触发isAuthenticated方法来检查并验证用户是否经过身份验证。问题是我正在使用如下所示的标志变量。

function isAuthenticated(req , res)
{
let  flag_auth = 0 ; 
     verifyIdToken(mytoken).then(user=>{
           console.log("User is signed in ")  ;
           flag_auth = 1 ; 
     })
     .catch(error=>{
           console.log("User not signed in yet ! ")
     })

return flag_auth  ;
}

假设VerifyIDToken是对服务器(firebase)的异步调用,它返回一个promise。由于这是一个异步调用,我返回的flag_auth将始终为0,因为ayanc调用需要一些时间才能完成,那时我的flag_auth将返回给调用者。

if(isAuthenticated(req, res))
        {
            console.log('login get from Signed in user ! ') ;
        }
        else{
            console.log("get request from not AUthenticated user ! ") ;
        }

所以每次isAuthenticated都会返回一个false值。在这种条件下我可以使用什么方法?如果我需要用promises实现一些东西,请用一个简短的代码片段解释一下如何去做吧?

1 个答案:

答案 0 :(得分:0)

在处理异步性时,您需要使用callbacks,因为只有他们才能访问将来检索的数据(异步)。我会尝试将您的应用程序重组为3个独立的部分:

/**
 * 1. check if the user is verified
 * this function accepts two callbacks on top of the user token.
 * one callback will be executed if the user is verified (2) and the other will be executed if the user is not (3)
 */
const checkIfUserIsVerified = (userToken, doThingsIfUserIsVerified, doThingsIfUserIsNotVerified) => {
  verifyIdToken(userToken)
    .then(doThingsIfUserIsVerified)
    .catch(doThingsIfUserIsNotVerified)
}

/**
 * 2. do things if the user is verified after checking
 */
const userIsVerified = user => {
  // this function has access to the user that verifyIdToken returns
  console.log('this function has access to the verified user: ', user)
}

/**
 * 3. do things if the user is not verified after checking
 */
const userIsNotVerified = error => {
  // this function has access to the error that was thrown when verifyIdToken tried verifying userToken
  console.error(error)
}

// now you can put everything together with mytoken (or whatever token you want to verify):
checkIfUserIsVerified(mytoken, userIsVerified, userIsNotVerified)

编辑:这是使用ES2017 async / await

checkIfUserIsVerified的更简单,更易读的替代方法
const checkIfUserIsVerified = async (userToken, doThingsIfUserIsVerified, doThingsIfUserIsNotVerified) => {
  try {
    const user = await verifyIdToken(userToken)
    doThingsIfUserIsVerified(user)
  } catch(error) {
    doThingsIfUserIsNotVerified(error)
  }
}