async函數(asynchronous 異步的)

async函數(asynchronous 異步的)ajax

同步:異步

console.log(1);
console.log(2);
console.log(3);
console.log(4);
//依次打印1 2 3 4;

異步 ajax 文件讀取io操做:async

console.log(1);
    console.log(2);
    setTimeout(function(){
        console.log(3000);
    },3000);
    console.log(3);
    console.log(4);
    //先打印1 2 3 4,隔三秒後打印3000;

async函數返回的是resolve狀態的Promise對象:函數

async function fn(){
        return "abc";
    }
    let result=fn();
    console.log(result);//打印:Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "abc"}。

Promise 對象:code

let p = new Promise(function(resolve,reject){
        resolve("abc");
    });
            
    p.then(function(data){
        console.log(data);//打印abc。
    });

async函數裏面的返回值傳遞給then方法:對象

async function fn(){
        return "123";
    }
    let p1 = fn();
    p1.then(function(data){
        console.log(data);//打印123.
    });

async函數用來處理異步:同步

function one(){
        return new Promise(function(resolve,reject){
            setTimeout(function(){
            console.log("one_3000");
            resolve("one_3000");
            },3000);
        })
    }
            
    function two(){
        return new Promise(function(resolve,reject){
            setTimeout(function(){
            console.log("two_2000");
            resolve("two_2000");
            },2000);
        })
    }
            
//await只能出如今異步函數裏面, 
    async function shunxu(){
        console.log("start");
        let r1 = await one();
        console.log(r1);
        let r2 = await two();
        console.log(r2);
        return "end";
    }
        let p3 = shunxu();
        p3.then(r=>{
            console.log("結束");
        });
            
    //先打印start,三秒後打印兩次one_3000,打印完one_3000而後隔兩秒打印兩次two_2000和結束;
相關文章
相關標籤/搜索