在声明之前如何在 Promise 链中使用变量?
我在使用 Promise 时遇到了以下代码。并且它工作正常。
我已经粗略地阅读了如何在节点上运行异步/等待代码。但是,在下面的代码中,如何在 .then()
函数内访问 session
变量?这段代码的工作仅仅是偶然,还是节点如何运行异步/等待代码使 session
变量在 .then()
函数中可用?
async function asyncFunction(
cb: (filePath: string, session: Session) => Promise<any>,
) {
readFile().then(filePath => cb(filePath, session));
const session = await verifyToken();
}
I came across the following code while working with promises. And it works correctly.
I have read shallowly on how async/await code is run on node. But, in the following code, how is the session
variable accessible inside the .then()
function? Is it just by sheer chance that this code works or is there something about how node runs async/await code that makes the session
variable available inside the .then()
function?
async function asyncFunction(
cb: (filePath: string, session: Session) => Promise<any>,
) {
readFile().then(filePath => cb(filePath, session));
const session = await verifyToken();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。如果
verifyToken
花费的时间比readFile
的时间长,session
将当.then()
回调运行时,未初始化,您将收到异常。此问题的正确解决方案是
Promise.all
,并且不使用回调:Yes. If
verifyToken
takes longer thanreadFile
,session
will not be initialised when the.then()
callback runs and you'll get an exception.The proper solution for this problem is
Promise.all
, and not using a callback:这是变量作用域的完美示例。在你的情况下,这个代码很有可能有效。由于
readFile
花费的时间比verifyToken
更长。因此,session
变量在then
函数中获得回调之前启动。如果
verifyToken
花费的时间比readFile
更长(即使只是一毫秒),那么它会抛出Cannot access variable before初始化
错误。This is a perfect example of variable scope. In your case this is a sheer chance that this code works. Since the
readFile
takes longer thanverifyToken
. As a result, thesession
variable is initiated before getting callback inthen
function.In case the
verifyToken
takes longer thatreadFile
(even just by a milli-second), then it would throwCannot access variable before initialization
Error.