Home > OS >  Promise not working, but Async/Await method working
Promise not working, but Async/Await method working

Time:01-16

I'm trying to figure out why I'm not able to retrieve data from the postgres database.

It works when I use async await, but when I try to to use Promise with .then(result).catch(error), it's not working.

Console log gives me Promise { <pending> }

getUsers

your text`const db = require("../config/db");

const getUsers = () => {
  const query = "SELECT * FROM users";
  const users = db
    .query(query)
    .then((result) => {
      return result.rows;
    })
    .catch((error) => {
      return error.message;
    });
  return users;
};

module.exports = {
  getUsers,
};

index.js (Using Promise) -- Doesn't work.

const { getUsers } = require('../helpers/users')

export default function Home(props) {
  return (
    <ul>
      {props.name}
      {props.users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}

    </ul>
  )
}

export function getServerSideProps(context) {

  const users = getUsers()
    .then((result) => {
      return result.rows;
    })
    .catch((error) => {
      return error.message;
    })

  return {
    props: {
      users
    }
  }
}

index.js (Using Async/Await) -- Works.

export async function getServerSideProps(context) {

  const users = await getUsers()

  return {
    props: {
      users
    }
  }
}

CodePudding user response:

That should work (according the Next doc getServerSideProps is async function). So just add async keyword and return promise from that function:

export async function getServerSideProps(context) {

  return getUsers()
    .then((result) => {
      return {props:{user:result.rows}};
    })
    .catch((error) => {
      return {props:{user:error.message}};
    })
}

CodePudding user response:

Thank you Andrey and Bergi.

Since it's Promise, I did not have to include the async, but the rest of the code did indeed work!

export function getServerSideProps(context) {

  getUsers()
    .then((result) => {
      return {
        props: {
          users: result
        }
      }
    })
    .catch((error) => {
      return {
        props: {
          error: error.message
        }
      }
    })
}
  • Related