了解TypeScript的async,await,promise(第1篇)


 

 參考地址:https://blog.csdn.net/u012863664/article/details/77881921

 

先來一段Promise代碼:

function timeout(ms:number){
    return new Promise((resolveCallback, rejectCallback) =>{
        resolveCallback(8888); ///此處,執行then里面的 第1個 匿名函數
        rejectCallback(7777);///此處,執行then里面的 第2個 匿名函數
    });
}

timeout(100)
.then( (value1)=>{ console.log(`I am resolveCallback: value1:${value1}`); }, (err)=>{
    console.log("I am rejectCallback: " + err);
});

 then里面第1個參數是一個 匿名回調函數,這個匿名回調函數就對應 Promise 里面,第一個參數 resolveCallbacke.
 resolveCallback是什么,取決於 then 里面定義了啥。。。
rejectCallback同理。

 

 

 

話不多說,先上一段代碼:

了解一下 async,await 基本語法

async函數內部return語句返回的值,會成為then方法回調函數的參數

async函數內部拋出錯誤,會導致返回的 Promise 對象變為reject狀態,
拋出的錯誤對象會被catch方法回調函數接收到

function getData(){
    return "syy";
}

console.log(getData());  //syy

async function getData2(){
    return "syy2";
}
console.log(getData2());  // Promise { resolved }
// 
getData2().then(data =>{console.log(data)});  //syy2

 

 

 

interface TEST_TYPE{
    name:string,
    age:number
}
let testA = <TEST_TYPE>{
    name:"henry",
    age:666
}

function changeA(testA:TEST_TYPE)
{
    testA.age = 777;
//    throw new Error("changeA new a error");  
    return testA;////特別注意返回的數據,我們在外部 then里面捕獲...包括異常
}

async function testAsync(testA:TEST_TYPE)
{
//    throw new Error("testAsync new a error.")
    let testB = await changeA(testA);
//    testB.age = 333;
    testB.name = "明天要交作業";
    return testB;
//    return testA ;
}

const result1 = testAsync(testA);
result1
.then( retValue=>{
    console.log(retValue);
    console.log(retValue.name);
    console.log(retValue.age);},
    reject=>{
        console.log("reject. It must be some error happen");
        console.log(reject);
    }
).catch(err=>{
    console.log("catch some error.");
    console.log(err);
});

 

在來個例子,來理解一下 程序是如何運行的

async function sleep(interval:number){
    return new Promise(resolve=>{
      setTimeout(resolve,interval);
    })
    .then(resolve2=>{console.log("finish resolve2.")},
      reject2=>{console.log("reject2")});
}
  
async function one2XInAsync(interval:number=100){
    for(let i=1;i<=interval;i++){
        console.log("one2FiveInAsync:-----------" + i);
        if(i==3)
        {
        throw new Error("i==3 break");
        }
        await sleep(2000);
    }
}
  
one2XInAsync(20)
  .then(resolve3=>{
    console.log("resolve3");
    console.log(resolve3);
  }, reject3=>{
    console.log("reject3");
    console.error(reject3);
});

 

繼續貼一段代碼

let testNum = 1+1;
function takeLongTime(){
    return new Promise(resolve =>{
        setTimeout( ()=>{
            resolve("Hello world");
        }, 4000);
    });
}

async function test1(){
    let t1 = await takeLongTime();
    console.log(testNum);
    console.log(t1);
}
test1();

 

 

單一的 Promise 鏈並不能發現 async/await 的優勢,但是,如果需要處理由多個 Promise 組成的 then 鏈的時候,優勢就能體現出來了(很有意思,Promise 通過 then 鏈來解決多層回調的問題,現在又用 async/await 來進一步優化它)。

假設一個業務,分多個步驟完成,每個步驟都是異步的,而且依賴於上一個步驟的結果。我們仍然用 setTimeout 來模擬異步操作:
function takeLongTime(n:number){
    return new Promise(resolve=>{
        setTimeout(()=>resolve(n+1000),n);
    });
}

function step1(n:number){
    console.log(`step1 with ${n}`);
    return takeLongTime(n);
}

function step2(n:number){
    console.log(`step2 with ${n}`);
    return takeLongTime(n);
}

function step3(n:number){
    console.log(`step3 with ${n}`);
    return takeLongTime(n);
}


/**采用Promise方式實現 */
function doIt1() {
    console.time("doIt1");
    const time1 = 300;
    step1(time1)
        .then(time2 => step2(<number>time2))
        .then(time3 => step3(<number>time3))
        .then(result => {
            console.log(`result is ${result}`);
            console.timeEnd("doIt");
        });
}

doIt1();
// step1 with 300
// step2 with 1300
// step3 with 2300
// result is 3300
// doIt: 3908.552001953125ms
// doIt: 3908.640ms



async function doIt2(){
    console.time("doIt2");
    const time1 = 400;
    const time2 = await step1(time1);
    const time3 = await step2(<number>time2);
    const result = await step3(<number>time3);
    console.log(`result is ${result}`);
    console.timeEnd("doIt2");
}

doIt2();
// step1 with 400
// step2 with 1400
// step3 with 2400
// result is 3400
// doIt2: 4211.223876953125ms
// doIt2: 4212.416ms

 

 

 

回顧一下匿名函數

const sleep1 = (timeout:number=2000) =>{console.log("[sleep1] a non name function,with a default params value:" , timeout);};

const sleep2 = (timeout=2000) =>{console.log("[sleep2] a non name function,with a default params value:" , timeout);};

const sleep3 = () =>{
    console.log("[sleep3] a non name function,with no params.");
};
const sleep4 = () =>console.log("[sleep4] a non name function,with no params.");

sleep1();
sleep1(666);
sleep2();
sleep2(777);
sleep3();
sleep4();
[sleep1] a non name function,with a default params value: 2000
[sleep1] a non name function,with a default params value: 666
[sleep2] a non name function,with a default params value: 2000
[sleep2] a non name function,with a default params value: 777
[sleep3] a non name function,with no params.
[sleep4] a non name function,with no params.


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM