Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

JavaScript Help with understanding how to use async, await and promises

Exabyte

Coder
I would like to ask for a little help with understanding the concept of promises and how async/await work. This is my second attempt at trying to understand and I have spent a lot of time Googling and reading but am still considerably confused. This time I need to understand because the functions related to the Origin Private File System (OPFS) feature that i am trying to use, make use of the 'await' keyword.

So far, I understand that promises are a way to request an action or result of a function in a way that does not otherwise block the execution of the application. The request happens "in the background" so to speak, and when the request has been completed, the promise is "fulfilled". The concept appears to be sound, but understanding its implementation is very confusing. I understand that a promise function (or whatever you call that nested messy construct) returns a promise object, and although I can expand the object and see my result in the console log, apparently there is no method by which one can get at the result? So of what use is that?

I have been told that async/await is "sugar candy" for promises to make them easier to use and indeed the syntax does seem to be cleaner. However, I am still vague as to what this is actually doing? As a practical example, I am trying to take the first step in OPFS of getting a reference to its root directory. In particular, I am trying to follow this:

The origin private file system | Articles | web.dev

As can be seen, the examples use the 'await' keyword, but none seem to mention 'async'. So trying to use the example as it stands in my function:

Code:
class TapeLibMgr {

    #OPFSroot;

    constructor(){
        this.#OPFSroot = "";
    }

    showTapeLibMgrLog(){
        this.#OPFSroot = await navigator.storage.getDirectory();
        console.log("OPFS: ", this.#OPFSroot);
    }

}

returns and error saying :

SyntaxError: await is only valid in async functions and the top level bodies of modules

So I changed it a bit and created a function with the 'async' keyword:

Code:
]class TapeLibMgr {

    #OPFSroot;

    constructor(){
        this.#OPFSroot = "";
        (async () => await this.init())();
    }

    async init() {
        this.#OPFSroot = await navigator.storage.getDirectory();      
    }

    showTapeLibMgrLog(){
        console.log("OPFS: ", this.#OPFSroot);
    }

}

So now when I call showTapeLibMgrLog() the result is and empty variable. Then, based on information I found on line here:


I added a line of code:

Code:
class TapeLibMgr {

    #OPFSroot;

    constructor(){
        this.#OPFSroot = "";
        (async () => await this.init())();
    }

    async init() {
        this.#OPFSroot = await navigator.storage.getDirectory();      
    }

    showTapeLibMgrLog(){
        console.log("OPFS: ", this.#OPFSroot);
    }

}

Now it works, but i don't understand WHY it works or what that extra line is doing?

In short, I understand the concept somewhat, but don't understand how to access the results of what I am trying to do in an asynchronous manner, so quite frankly, I am still very much stumbling in the dark. Any help in understanding the concept a bit better and specifically how to implement async functions in practice - for example how the above idea should be implemented - would be appreciated.
 
Yes and WebMD, both useful resources.

I actually spent all day and into the early hours on this yesterday and it paid of because finally, by 3am in the morning got what I needed working.

Firstly, although having an IIFE in the constructor seems to work, the advice I got on the JavaScript IRC channel seems to be that this is a bad idea so I now removed it. Instead, I am calling an async ini() function.

Secondly, it seems that assigning and referring to global class variables, such as the private this.#OPFSroot that set up will usually fail because the async functions may not have returned results (fulfilled their promises) yet so subsequent async calls were reading the variable as 'undefined'.

I also hadn't properly set up the .then chain to correctly await the result of one function before asnchronously calling the next. Hence the first step or two would work, but subsequent steps returned undefined or empty results.

I was determined and eventually had a breakthrough in my understanding of things and was able to solve the problems and arrange the functions and callbacks (.then sections) in an appropriate way so that I got the result that was expected. Today I have been reading another helpful async Javascript tutorial book which has helped to re-enforce my understanding of the concepts and the reason for the problems that I had enoucntered. Hopefully this eill help me move forward.

I do still have questions. For example, I am working with Origin Private File System (OPFS - another new concept for me). Methods to get file handles and work with files are all async calls, which means the class will have be comprised of async funcions. Somehow, I would like to store a reference to the root of OPFS as well as the directory and asociated with the class instance somehow within it. As I have discovered, because of the async nature of the associated functions, this cannot be done using ordinary Javascript this.variables in the construcor, so how would I manage to store this information within the class so it doesn't have to be repeatedly fetched from the OPFS?
 
Last edited:

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom