异步函数返回 [object Promise] [英] Async function returns [object Promise]
问题描述
我试图返回一个异步函数,但我要么得到 promise: <{ PENDING } >
或 [object Promise]
而不是 [object Object]
I'm trying to return an async function but I either get promise: < { PENDING } >
or [object Promise]
instead of [object Object]
我尝试使用 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]
};
如果我从函数中去掉 async
和 await
并从 controller<中提取我的低级
db.query
/code> case 到它自己的 async function
我只是得到 promise: <{ PENDING } >
所以我认为这是因为顶级函数没有等待它解决.但是,当我使这些函数异步时,它们会返回对我的静态数据的承诺.我无法理解这些嵌套的 Promise/异步函数.
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.
推荐答案
您不能使异步代码同步.
You cannot make asynchronous code synchronous.
await
关键字让您可以编写看起来是同步的代码,但实际上是异步的.
The await
keyword lets you write code that looks synchronous, but is really asynchronous.
您只能在 async
的函数中使用 await
.
You can only use await
inside a function which is async
.
为了使 await
工作,所有 async
函数返回承诺.这些承诺解析为函数的返回值.
To make await
work, all async
functions return promises. Those promises resolve to be the return value of the function.
简而言之:您具有正常和预期的行为,并且您无法阻止 async
函数返回承诺.
In short: You have the normal and expected behaviour, and you can't prevent an async
function from returning a promise.
这篇关于异步函数返回 [object Promise]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!