在声明之前如何在 Promise 链中使用变量?

发布于 2025-01-17 04:04:24 字数 485 浏览 1 评论 0原文

我在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小糖芽 2025-01-24 04:04:25

这段代码的工作仅仅是偶然吗?

是的。如果 verifyToken 花费的时间比 readFile 的时间长,session.then() 回调运行时,未初始化,您将收到异常。

此问题的正确解决方案是 Promise.all,并且不使用回调:

async function asyncFunction(): Promise<[filePath: string, session: Session]> {
    return Promise.all([readFile(), verifyToken()]);
}

Is it just by sheer chance that this code works?

Yes. If verifyToken takes longer than readFile, 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:

async function asyncFunction(): Promise<[filePath: string, session: Session]> {
    return Promise.all([readFile(), verifyToken()]);
}
谁与争疯 2025-01-24 04:04:25

这是变量作用域的完美示例。在你的情况下,这个代码很有可能有效。由于 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 than verifyToken. As a result, the session variable is initiated before getting callback in then function.

In case the verifyToken takes longer that readFile (even just by a milli-second), then it would throw Cannot access variable before initialization Error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文