Async function returns [object Promise]

耗尽温柔 提交于 2020-07-04 02:46:57

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/55696387/async-function-returns-object-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!