了解 NodeJS 上的异步/等待 [英] Understanding async/await on NodeJS
问题描述
我认为我对它的理解可能会受到我对 .NET 的 async/await
的体验的影响,所以我想要一些代码示例:
I think my understanding of it might be affected by my experience with .NET's async/await
, so I'd like some code example:
我试图让快速控制器在返回响应之前等待 5 秒:
I'm trying to make a express controller wait 5 seconds before returning the response:
const getUsers = async (ms) => {
var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
await wait(ms);
};
export const index = (req, res) => {
async () => {
await getUsers(5000);
res.json([
{
id: 1,
name: 'John Doe',
},
{ id: 2,
name: 'Jane Doe',
},
]);
};
};
这段代码不起作用,浏览器一直在加载和加载,从不显示任何东西.
This code doesn't work, the browser keeps loading and loading and never shows a thing.
我基于 getUser 函数>this SO answer,以及控制器方法,基于我对其工作原理的(错误的)理解,所以我想要一些澄清和更正:
The getUser
function I built based on this SO answer, and the controller method, based on my (mistaken) understanding of how it works so I'd like some clarification and correction:
1.我什么时候应该使用await
?
据我所知,您应该在 async
函数调用之前使用 await
.这个对吗?另外,为什么我可以在返回承诺的非异步函数之前调用 await ?
To my understanding, you should use await
before an async
function call. Is this correct? Also, why can I call await before a non-async function that returns a promise?
2.我什么时候应该使用 async
?
据我所知,您将函数标记为 async
函数,以便可以使用 await
关键字调用它.这个对吗?另外,[为什么] 我必须将我的 await getUsers(5000)
调用包装在匿名异步函数中?
To my understanding, you mark a function as an async
one so that it can be called with the await
keyword. Is this correct? Also, [why] do I have to wrap my await getUsers(5000)
call in an anonymous async function?
推荐答案
澄清几个疑惑 -
- 您可以将
await
与任何返回承诺的函数一起使用.您正在等待的函数不一定是async
. - 当您想在该函数中使用
await
关键字时,您应该使用async
函数.如果您不打算在函数内使用await
关键字,那么您不需要将该函数设为async
. async
函数默认返回一个 promise.这就是您能够await
async
函数的原因.
- You can use
await
with any function which returns a promise. The function you're awaiting doesn't need to beasync
necessarily. - You should use
async
functions when you want to use theawait
keyword inside that function. If you're not gonna be using theawait
keyword inside a function then you don't need to make that functionasync
. async
functions by default return a promise. That is the reason that you're able toawait
async
functions.
来自 MDN -
当异步函数被调用时,它会返回一个 Promise.
When an async function is called, it returns a Promise.
就你的代码而言,可以这样写 -
As far as your code is concerned, it could be written like this -
const getUsers = (ms) => { // No need to make this async
return new Promise(resolve => setTimeout(resolve, ms));
};
// this function is async as we need to use await inside it
export const index = async (req, res) => {
await getUsers(5000);
res.json([
{
id: 1,
name: 'John Doe',
},
{ id: 2,
name: 'Jane Doe',
},
]);
};
这篇关于了解 NodeJS 上的异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!