async function - await not waiting for promise

前端 未结 4 1207
生来不讨喜
生来不讨喜 2020-12-30 22:52

I\'m trying to learn async-await. In this code -

const myFun = () => {
    let state = false;

    setTimeout(() => {state = true}, 2000);

    return         


        
4条回答
  •  难免孤独
    2020-12-30 23:37

    This is my routine dealing with await and async using a Promise with resolve and reject mechanism

        // step 1 create a promise inside a function
        function longwork()
        {
            p =  new Promise(function (resolve, reject) {
                result = 1111111111111 // long work here ; 
    
                if(result == "good"){
                    resolve(result);
                }
                else
                {
                    reject("error ...etc")
                } 
            })
    
            return p
        }
    
        // step 2 call that function inside an async function (I call it main)and use await before it
        async function main()
        {
             final_result = await longwork();
             //..
    
        }  
    
        //step 3 call the async function that calls the long work function
        main().catch((error)=>{console.log(error);})
    

    Hope that saves someone valuable hours

提交回复
热议问题