了解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 函数38975138 / is-using-async-in-settimeout-valid#answer-39027151>这个SO答案,以及控制器方法,基于我(错误)理解它的工作方式,所以我想澄清一下和更正:
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。我应该何时使用等待
?
1. when should I use await
?
根据我的理解,你应该使用 await
在 async
函数调用之前。它是否正确?另外,为什么我可以在返回promise的非异步函数之前调用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
?
2. When should I use 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?
推荐答案
要清除一些疑问 -
To clear a few doubts -
- 您可以使用
await
包含任何返回promise的函数。您正在等待的功能不一定是async
。 - 您应该使用
async
当你想在该函数中使用await
关键字时的函数。如果您不打算在函数中使用等待
关键字,那么您不需要创建该函数async
。 -
async
默认情况下,函数返回一个promise。这就是你能够等待
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屋!