首页 > 其他分享 >兼收并蓄 TypeScript - 进阶: async/await

兼收并蓄 TypeScript - 进阶: async/await

时间:2024-09-20 12:27:02浏览次数:1  
标签:function resolve 进阶 await webabcd TypeScript Promise async

源码 https://github.com/webabcd/TypeScriptDemo
作者 webabcd

兼收并蓄 TypeScript - 进阶: async/await

示例如下:

advanced\async_await.ts

{
    /**
     * async/await - 用于异步编程(非多线程)
     *   async function 返回的是 Promise 对象
     *   await 用于等 Promise 对象或者 thenable 对象,其只能放在 async function 中
     *   所谓的 thenable 对象,就是定义了 then() 方法的对象
     */

    // async function 的说明
    // p1() 等价于 p2()
    function p1() {
        return Promise.resolve("webabcd");
    }
    async function p2() { // 对于 async function 来说,会用 Promise.resolve() 来包装返回对象
        return "webabcd";
    }
    console.log(p1(), p2());
    // Promise {<resolved>: 'webabcd'} Promise {<resolved>: 'webabcd'}


    // await 的说明(只能放在 async function 中)
    async function sleep(ms:number) {
        await new Promise((resolve) => {
            setTimeout(resolve, ms);
        });
    }
    async function a(value:string, ms:number) {
        await sleep(ms);
        console.log(value);
    }
    let asyncFunction = a("webabcd", 1000);
    console.log(asyncFunction); // 1 秒钟之后会打印 webabcd
    // 这里打印的是 Promise {<pending>}


    // 如果在非 async function 中,想实现 await 的功能怎么办,可以通过 promise 的 then() 来实现
    async function b(value:string, ms:number) {
        await new Promise(r => setTimeout(r, 1000)); // 等 1 秒
        return value; // 对于 async function 来说,会用 Promise.resolve() 来包装返回对象
    }
    let promise = b("wanglei", 1000);
    promise.then(v => console.log(v));
    // 1 秒钟之后会打印 wanglei


    // 如果一个类有 then() 方法,则这个类的实例化对象是 thenable 对象
    // await 除了用于等待 Promise 对象外,也可以用于等待 thenable 对象
    // await 一个 thenable 对象时,实际上等待的是这个对象的 then() 方法
    class Sleep {
        constructor(public timeout:number) {

        }
        then(resolve: (value: string) => void, reject?: (value: string) => void) {
            setTimeout(() => resolve("diandian"), this.timeout);
        }
    }
    (async () => {
        console.log(await new Sleep(1000)); // 1 秒钟之后会打印 diandian
    })();


    // 演示如何对 await 做 try/catch
    let c = () => {
        return new Promise((resolve, reject) =>{
            setTimeout(()=>{
                let x = new Date().getTime() % 2;
                if (x == 0) {
                    return resolve("fulfilled");
                } else if (x == 1) {
                    return reject("rejected");
                }
            },1000);
        });
    };
    (async () => {
        try {
            // 如果走到 Promise 的 resolve() 则可以正常收到返回数据
            console.log("try: " + await c()); // try: fulfilled
        } catch(e) {
            // 如果走到 Promise 的 reject() 则会捕获到异常
            console.log("catch: " + e); // catch: rejected
        }
    })();


    // 并发执行多个 Promise
    let i = async () => {
        return Promise.resolve("iii");
    };
    let j = async (ms:number) => {
        return new Promise((resolve) => {
            setTimeout(() => resolve("jjj"), ms);
        });
    };
    let k = async (ms:number) => {
        return new Promise((resolve, reject) => {
            let x = new Date().getTime() % 2;
            if (x == 0) {
                setTimeout(() => resolve("kkk"), ms);
            } else if (x == 1) {
                setTimeout(() => reject("lll"), ms);
            }

        });
    };
    (async () => {
        try {
            // 通过 Promise.all() 并发执行多个 Promise
            let [x, y, z] = await Promise.all([i(), j(1000), k(1000)]);
            console.log(x, y, z); // iii jjj kkk
        } catch (e) {
            // 有一个 Promise 走到了 reject(),这里就会捕获到异常
            console.log(e); // lll
        }
    })();
}

源码 https://github.com/webabcd/TypeScriptDemo
作者 webabcd

标签:function,resolve,进阶,await,webabcd,TypeScript,Promise,async
From: https://www.cnblogs.com/webabcd/p/18422272/typescript_advanced_async_await

相关文章

  • 兼收并蓄 TypeScript - 进阶: iterator, generator
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-进阶:iterator,generator示例如下:advanced\iterator_generator.ts{/***iterator-迭代器(可迭代对象有Array,TypedArray,Map,Set,String)*next()-迭代到......
  • 兼收并蓄 TypeScript - 进阶: proxy, reflect
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-进阶:proxy,reflect示例如下:advanced\proxy_reflect.ts{//Proxy-代理(拦截目标对象的属性操作和函数操作)lettarget={name:'webabcd',age:40,......
  • 兼收并蓄 TypeScript - 第三方库: 类型声明
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-第三方库:类型声明示例如下:third\typeDeclaration.ts/**类型声明用于TypeScript调用JavaScript*类型声明定义在.d.ts声明文件中*比如aes.js文件,其对应的声明文件为ae......
  • 兼收并蓄 TypeScript - 第三方库: crypto-js
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-第三方库:crypto-js示例如下:third\cryptojs.ts/**本例以在TypeScript中使用crypto-js为例*crypto-js是一个纯js项目,是不能直接在typescript中使用的,需要相应的.d.ts......
  • 兼收并蓄 TypeScript - 基础: number
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:number示例如下:basic\number.ts{//将指定类型的数据转换为number类型console.log(Number("100"),Number(true),Number({}),Number([]));//1001NaN0//......
  • 兼收并蓄 TypeScript - 基础: string
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:string示例如下:basic\string.ts{leta="\x7A";//十六进制的“7A”是字符“z”letb="\u{7A}";//十六进制的“7A”是字符“z”letc="\u{738B}";......
  • 兼收并蓄 TypeScript - 基础: symbol
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:symbol示例如下:basic\symbol.ts{//Symbol()是一个全局函数,返回一个唯一的Symbol值consta=Symbol();constb=Symbol();//b与a不同constc=Sy......
  • 兼收并蓄 TypeScript - 基础: array
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:array示例如下:basic\array.ts{//array-数组//创建数组letarray1:number[]=[1,2,3];letarray2:Array<number>=[1,2,3];letarray3:Ar......
  • 兼收并蓄 TypeScript - 基础: set
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:set示例如下:basic\set.ts{//set是一个集合,先进先出,不会插入重复数据,数据支持类型的多样性//常规操作有add(),delete(),has(),clear(),size等letmySet=......
  • 兼收并蓄 TypeScript - 基础: map
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:map示例如下:basic\map.ts{//map是一个key/value集合,先进先出,遇到重复键值则后面的会覆盖前面的,key和value都支持类型的多样性//常规操作有set(),get(),dele......