Is this Async Await redundant?

I’m trying to make sure of something that’s really, really basic. But I’m having trouble finding the answer to.

I have a userController with an async function. It has a variable that awaits a function that queries a database table for user accounts in the model file. The model file is just a regular function that returns function getUser = () => db(‘users’).select(’*’).

In this strict scenario, I do not need to make the function that queries the database to be async, right? That’s taken care of by the controller’s async function. And likewise, if I decided to implement the async-await on the function that queries the database, I can remove the async-await implemention from the controller.

If I understand your question, if you are performing an async action, you need to handle it, if you need that value synchronously.

using the jsonplaceholder site for an easy async action

const fetchMessage = () =>
    .then(response => response.json())
    .then(json => json);

const showMessage1 = () => {
  const message = fetchMessage();
  console.log('message 1', message);

// a promise

That fetch returns with a Promise that we didn’t handle.

const showMessage2 = () => {
  const message = fetchMessage()
    .then(message => console.log('message 2', message));

// the message object I wanted

This handles the Promise.

const showMessage3 = async () => {
  const message = await fetchMessage();
  console.log('message 3', message);

// the message object I wanted

This also handles the Promise. async/await is just syntactic sugar for a Promise. It does the same thing but makes “synchronous looking code”.

If I understand your question, I think your asking about this case?

const callFetch4 = () => fetchMessage();

const showMessage4 = async () => {
  const message = await callFetch4();
  console.log('message 4', message);

// the message object I wanted

So, that seems to work. Even when abstracted by a calling function. I don’t know why - I don’t know if it propagates that way. I know that there is sometimes an implicit await with return - I don’t know if that is a factor.

But now you have me curious. You can mess around with these functions here.

I guess on reflection, the last example isn’t as weird as I was thinking. callFetch4 is just returning a Promise. And then in showMessage4, it gets handled.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.