zoukankan      html  css  js  c++  java
  • 了解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.


  • 相关阅读:
    js格式化货币金额
    Mac idea maven 创建web项目
    The string "--" is not permitted within comments.
    Java从数据库读取页面树形菜单
    oracle 查询重复数据并且删除, 只保留一条数据重复数据
    SSM框架---使用MyBatis Generator自动创建代码
    前端 NPM常用命令行
    前端常用命令行
    Angular 常用命令行
    JS/JQuery 文档加载完成
  • 原文地址:https://www.cnblogs.com/music-liang/p/12742963.html
Copyright © 2011-2022 走看看