ReactJS Promise resolve() doesn't pass the value to .then() but reject() pass the value to .catch()

Viewed 165

I am trying to make a project with ReactJS and AWS Cognito. I am using all auth functions in auth.js folder. In login screen, I am trying to get the session information from auth.js like this:

auth.js

var getSessionInfo = async () => {
        await new Promise((resolve, reject) => {
            const user = Pool.getCurrentUser();
            if (user) {
                user.getSession((err, session) => {
                    if(err){
                        reject(err)
                    }else{
                        resolve(session)
                    }
                })
            } else {
                reject()
            }
        })
    }

and in login.js

getSessionInfo()
      .then(session => {
        console.log("session:", session)
        setIsAuth(true)

        if (isAuth) {
          history.push("/home")
        }
      })
      .catch(err => {
        console.log("err:", err)
      })

In login.js, .then(session => {...}) this session is always undefined. None of the resolves returns the values, no matter what I write in it.

But the fun part is if I use reject() instead of resolve() and use .catch() instead of .then() the values passes perfectly. If I can't find the cause of it I might use Promises this way.

2 Answers
  • The promise await is not being returned.
  • Therefore, even though the value is resolved, it's not being returned to the callback.
  • Add return here:
return await new Promise((resolve, reject) => {

The getSessionInfo forgets to return anything from the function, so the returned value is always undefined. You also don't have to await the promise as you are not using the result of the promise later on in the function.

Instantly return the promise and lose the async / await (which would make sense when you call the getSessionInfo function) to solve your issue.

const getSessionInfo = () => new Promise((resolve, reject) => {
  const user = Pool.getCurrentUser();
  if (user) {
    user.getSession((err, session) => {
      if (err) {
        reject(err)
      }
      resolve(session);
    });
  }
  reject();
});

Down here async / await would make sense as you want to actually wait for the value from getSessionInfo before continuing.

(async () => {
  try {
    const session = await getSessionInfo();
    console.log("session:", session)
    setIsAuth(true)
    if (isAuth) {
      history.push("/home")
    }
  } catch(error) {
    console.log("err:", err)
  }
})()
Related