当前位置:网站首页>JS promise, async, await simple notes

JS promise, async, await simple notes

2022-06-11 05:17:00 kankan231

promise demo

function getToken(username,pwd) {
        console.log("111")
        return new Promise(function (resolve, reject) {
            console.log("222")
            setTimeout(() => {
                console.log("333")
                if (username=="admin" && pwd=="123456"){
                    resolve("xxx")
                }else{
                    reject(" Wrong user name or password ")
                }

            }, 1000);

        })
    }
    console.log("444")
    getToken("admin","123456").then(function (token) {
        console.log("token:",token)
    }).catch(function (error) {
        console.log("error:",error)
    })
    console.log("555")

Output :

444
111 
222 
555 

333
token: xxx 
 

It can be seen from the results ,promise function The code in is executed synchronously , When calling resolve It will callback then, It will also pass parameters to then, call reject It will callback catch, It will also pass parameters to catch

async/await demo

function getToken(username,pwd) {
        console.log("111")
        return new Promise(function (resolve, reject) {
            console.log("222")
            setTimeout(() => {
                console.log("333")
                if (username=="admin" && pwd=="123456"){
                    resolve("xxx")
                }else{
                    reject(" Wrong user name or password ")
                }

            }, 1000);

        })
    }

    async function asyncTest(){
        console.log("444")
        try {
            let token = await getToken("admin","123456")
            console.log("token:",token)
        }catch (e) {
            console.log("err:",e)
        }
        console.log("555")

    }

    let ret = asyncTest();
    console.log("ret:",ret)

Output :

444

111

222

ret: Promise { <state>: "pending" }

333

token: xxx

555

analysis : When used in a function await When a keyword , Function must be preceded by async keyword ,await The function of keywords is , When await The value of the following expression is a number / String and other common types ,await Get this value directly , When the value of the expression is promise Object time , Then wait for the promise object resolve or reject,await Will get resolve or reject Value , there try-catch It's used to deal with reject The situation of . It can be seen from the results ,async The function always automatically returns a promise object , When executed await When the sentence is , The function returns , etc. await The end will automatically execute the following remaining code

原网站

版权声明
本文为[kankan231]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110509285390.html