Home > Enterprise >  What does this async function do?
What does this async function do?

Time:06-26

I'm new to async/await in JS. This is an ionic react app I'm looking at and I'm not sure what it does. Can someone explain it to me like I'm 5?

const handleClick = async(e, operator) => {
        if(operator == "MC"){
            if(isPlatform("android")){
                 await Storage.remove({key:'history'})

            }else{
                window.localStorage.removeItem("history")
            }
            return false
        }else if(operator == "MR"){
            let storage = ""
            let parse = ""
            if(isPlatform("android")){
                let storage = await Storage.get({key:'history'})
                 parse = JSON.parse(storage.value)
            }else{
                let storage = await window.localStorage.getItem("history")
                parse = JSON.parse(storage)
            }
            setSumHistory(parse[0].expration)
            return false
            
        }}

CodePudding user response:

Since you ask for clarification for async/await I will cover that part.

If you add async to a function this means that the function will always return a promise. https://javascript.info/async-await

The handleClick function will wait on the following lines for a promise to resolve or reject.

await Storage.remove({key:'history'})
....
let storage = await Storage.get({key:'history'})
....
let storage = await window.localStorage.getItem("history")

If one of these calls gets rejected handleClick with throw an error since there is no try / catch block around these await calls. https://javascript.info/try-catch

Hope this will help you get a better understanding of async await in this code block.

CodePudding user response:

if there is a line that needs time to be resolved and the next line depends on on the results of that line of code, you need to await that line to complete by returning a promise. and to tell the function there is a line you need to resolve that will return a promise you need to add async to that function.

  • Related