Async/Await , simple example (typescript)

前端 未结 2 1219
终归单人心
终归单人心 2020-12-15 16:04

I am quite familiar with the async/await of c# and been using typescript for a year or so, can anyone please give a simple example explaining how it works on typescript??

相关标签:
2条回答
  • 2020-12-15 16:30

    The key is to use an ES6 Promise or something that implements the PromiseLike and PromiseConstructorLike interfaces found in lib.d.ts (Read more). A jQuery promise does not implement these interfaces so it won't work with that.

    Here's a simple example using an ES6 promise:

    function getStringFromWebServerAsync(url: string) {
        return new Promise<string>((resolve, reject) => {
            // note: could be written `$.get(url).done(resolve).fail(reject);`,
            //       but I expanded it out for clarity
            $.get(url).done((data) => {
                resolve(data);
            }).fail((err) => {
                reject(err);
            });
        });
    }
    
    async function asyncExample() { 
        try {
            const data = await getStringFromWebServerAsync("http://localhost/GetAString");
            console.log(data);
        }
        catch (err) {
            console.log(err);
        }
    }
    
    asyncExample();
    

    Note that any code containing an await statement needs to be within an async function and so I have wrapped the code in one. That said, an upcoming proposal adds "top-level await", which will be available in TypeScript 3.8. Read more here and see here for TypeScript details.

    0 讨论(0)
  • 2020-12-15 16:33

    Please note that you need to target ES6 in Typescript 1.7 to use async/await. With lower versions, Visual Studio outputs

    TS1308 'await' expression is only allowed within an async function.
    

    and

    TS1311 Async functions are only available when targeting ECMAScript 6 and higher.
    

    For more information see e.g. http://blogs.msdn.com/b/typescript/archive/2015/11/03/what-about-async-await.aspx

    0 讨论(0)
提交回复
热议问题