0

I'm trying to return an async function but I either get promise: < { PENDING } > or [object Promise] instead of [object Object]

I've tried returning the value using Promise.resolve(value), Promise.resolve().then(return value), return new Promise((resolve, reject) => {resolve(value)}

from top-level to bottom my code looks like:

//Top-Level
const getNext = require('getNext');
const next = getNext({
  page,
  value,
  name,
  id,
});


//getNext
const controllerMap = {
  intro: introController
};
async function getNext({ page, value, name, id}) {
  const controller = controllerMap[name];
  return await controller({
    page,
    value,
    name,
    id
  });
}

// Controller
async function introController({ page, value, id }) {
  switch(page)
    case 10:
      // Do something async ie:
      await db.query
    default: return intro[page]
};

If I take off async and await from the functions and extract my low-level db.query from the controller case into it's own async function I just get promise: < { PENDING } > so I'm thinking it's because the top level functions aren't waiting for it to resolve. However, when I make those functions async they return promises for my static data. I'm having trouble wrapping my head around these nested promises/async functions.

4
  • 1
    you have to await the call to getNext Commented Apr 15, 2019 at 19:58
  • The goal of async/await is to minimize how many times you actually have to explicitly create and .then() Promises. You need to use await alongside the async or use .then(). Commented Apr 15, 2019 at 20:00
  • 1
    @DanielA.White — They can't. You can only await inside an async function, and the call to getNext is not inside a function. Commented Apr 15, 2019 at 20:00
  • then make it one. Commented Apr 15, 2019 at 22:53

2 Answers 2

4

You cannot make asynchronous code synchronous.

The await keyword lets you write code that looks synchronous, but is really asynchronous.

You can only use await inside a function which is async.

To make await work, all async functions return promises. Those promises resolve to be the return value of the function.

In short: You have the normal and expected behaviour, and you can't prevent an async function from returning a promise.

Sign up to request clarification or add additional context in comments.

2 Comments

So how can I achieve the desired implementation? I need to make the db call inside that specific case and then perform logic on the results.
@Nathan you have to do the work in a .then() callback.
0

I solved this by adding an await to the top level getNext() aka

const next = await getNext({
  page,
  value,
  name,
  id,
});

which is inside an async router.post call. So the answer is: make sure all functions are async all the way to the top so that they wait for eachother.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.