Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can variable be used in promise chaining before declaration?

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();
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading