[英]Why use async without await in Javascript?
I have seen so many people defining async function without using await in it like this.我见过很多人定义 async 函数而没有像这样使用 await 。
async function authMiddleware(req, res, next) => {
try {
const token = req.query.token
const secret = process.env.JWT_SECRET
jwt.verify(token, secret)
} catch (err) {
return res.status(403).json({ message: MESSAGES.TOKEN_EXPIRED })
}
return next()
}
I've attached this code just for an example.我附上这段代码只是为了一个例子。 Please don't care the meaning of lines inside.
请不要在意里面的行的含义。
Is there any good point or use case of defining a function as async without any await
in javascript?在javascript中没有任何
await
情况下将函数定义为异步有什么好处或用例吗?
Possibly: is it possible that he intended to inform the user that it returns promise?可能:他是否有可能打算通知用户它返回承诺?
For you shown code, it does not make any sense, because it is - at least I assume - an express middleware and expressjs does not use the returned Promise of that middleware.对于您显示的代码,它没有任何意义,因为它 - 至少我假设 - 一个快速中间件,而 expressjs 不使用该中间件返回的 Promise。 And without an
await
in that async
middleware the only thing that changes is that the middleware returns a Promise
, and as expressjs does not use that returned Promise, so the async
keyword here is pointless and can be even harmful, if the something in authMiddleware
throws a not cached error.如果在
async
中间件中没有await
,唯一改变的是中间件返回一个Promise
,并且由于 expressjs 不使用返回的 Promise,所以这里的async
关键字毫无意义,甚至可能是有害的,如果authMiddleware
的东西抛出未缓存的错误。
And it does not make sense to use it without any reason
. without any reason
使用它是without any reason
意义的。 You can use async
and await
to convert an otherwise long-running synchronous process into smaller chunks so that other code can interleave, as await
/ async
allows you introduce some kind cooperative multitasking.您可以使用
async
和await
将其他长时间运行的同步进程转换为较小的块,以便其他代码可以交错,因为await
/ async
允许您引入某种协作多任务处理。 But only adding await
/ async
to a long-running task alone would not prevent you from blocking the event loop.但是仅将
await
/ async
添加到长时间运行的任务中并不能阻止您阻塞事件循环。
If you have a code like this:如果你有这样的代码:
function testA() { for( let i=0 ; i<10 ; i++) { console.log('testA', i) } } function testB() { for( let i=0 ; i<10 ; i++) { console.log('testB', i) } } testA(); testB(); console.log('finished');
Then you could use await
and async
to allow other code to interleave, by changing it to.然后,您可以使用
await
和async
来允许其他代码交错,方法是将其更改为。
async function testA() { for (let i = 0; i < 10; i++) { console.log('testA', await i) } } async function testB() { for (let i = 0; i < 10; i++) { console.log('testB', await i) } } Promise.all([ testA(), testB() ]).then(() => { console.log('finished'); })
What ESLint says with its rule require-await . ESLint 的规则是require-await 。
Asynchronous functions in JavaScript behave differently than other functions in two important ways:
JavaScript 中的异步函数在两个重要方面与其他函数的行为不同:
- The return value is always a Promise.
返回值始终是 Promise。
- You can use the await operator inside of them.
您可以在其中使用 await 运算符。
The primary reason to use asynchronous functions is typically to use the await operator, ...
使用异步函数的主要原因通常是使用 await 运算符,...
The async function declaration defines an asynchronous function — a function that returns an AsyncFunction object.
async 函数声明定义了一个异步函数——一个返回 AsyncFunction 对象的函数。 Asynchronous functions operate in a separate order than the rest of the code via the event loop, returning an implicit Promise as its result.
异步函数通过事件循环以与其余代码不同的顺序运行,返回一个隐式 Promise 作为其结果。 But the syntax and structure of code using async functions looks like standard synchronous functions.
但是使用异步函数的代码的语法和结构看起来像标准的同步函数。
It is clear that async functions are not only made for await use .很明显,异步函数不仅仅用于 await 使用。 Then, not having await in an async function is ok.
然后,在异步函数中没有 await 是可以的。 But... what is the point ?
但是……有什么意义?
I believe it is to use a synchronous function like a Promise.我相信是使用了像 Promise 这样的同步函数。 The following example is from javascript.info .
以下示例来自javascript.info 。
async function f() {
return 1;
}
f().then(alert); // 1
Would be the same as:将与以下相同:
async function f() {
return Promise.resolve(1);
}
f().then(alert); // 1
Is there any good point of defining a function as async without any reason in javascript?
在javascript中没有任何理由地将函数定义为异步有什么好处吗?
It may be used to make code more readable or easy to follow.它可用于使代码更具可读性或易于遵循。
Results client-side will not be impacted.结果客户端不会受到影响。
Above written code is intended to returning an implicit Promise as its result.
上面编写的代码旨在返回一个隐式 Promise 作为其结果。
Like喜欢
async function firstFunction(a , b) {
do some stuff here.....
}
function secondFunction(res){
do some stuff here.....
}
async function thirdFunction(items){
const data = await fetch('url here');
const result = await data.json();
do some stuff here........
}
so Here is the deal....
所以这里是交易....
firstFunction(2,3) . firstFunction(2,3) 。 then ((resOfFirst) => secondFunction(resOfFirst)) .
然后((resOfFirst) => secondFunction(resOfFirst)) 。 then ((resOfSecond) => thirdFunction(resOfSecond))
然后((resOfSecond) =>thirdFunction(resOfSecond))
Hope this will help.希望这会有所帮助。
For the example code provided, I guess the developer had intentions of making it asynchronous (not blocking event-loop) in the future but he didn't know an easy way to do so.对于提供的示例代码,我猜开发人员打算在将来使其异步(不阻塞事件循环),但他不知道这样做的简单方法。 The thing is
jwt.verify
doesn't provide a Promise
based API, it accepts an optional third callback parameter in which case it will be executed asynchronously.问题是
jwt.verify
不提供基于Promise
的 API,它接受一个可选的第三个回调参数,在这种情况下它将异步执行。 Again I guess the developer wasn't confident about using callback API, or he has been religious about using async/await
wherever possible.我再次猜想开发人员对使用回调 API 没有信心,或者他一直在尽可能使用
async/await
。
A possible solution using async/await
, could be to promisify jwt.verify
and await
on that promisified function call:使用
async/await
一个可能解决方案,可能是在该 promisified 函数调用上promisify jwt.verify
和await
:
const verifyJwtAsync = Bluebird.promisify(jwt.verify);
async function authMiddleware(req, res, next) => {
try {
const token = req.query.token
const secret = process.env.JWT_SECRET
await verifyJwtAsync(token, secret)
} catch (err) {
return res.status(403).json({ message: MESSAGES.TOKEN_EXPIRED })
}
return next()
}
A simpler callback-based solution is as follows:一个更简单的基于回调的解决方案如下:
async function authMiddleware(req, res, next) => {
const token = req.query.token
const secret = process.env.JWT_SECRET
jwt.verify(token, secret, function(err) {
if (err) res.status(403).json({ message: MESSAGES.TOKEN_EXPIRED });
else next();
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.