Async/Await,简单示例(打字稿) [英] Async/Await , simple example (typescript)

查看:86
本文介绍了Async/Await,简单示例(打字稿)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#的异步/等待非常熟悉,并且使用打字稿已经一年左右了,任何人都可以举一个简单的示例来说明它在打字稿上是如何工作的吗? 在此先感谢您,希望能找到一些帮助并实施相同的帮助

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?? Thanks in advance , looking forward to find some help and implement the same


更新
如果该示例包含angular/jquery promise,将非常有帮助,因为它将清楚地展示实际实现方式


UPDATE
it would be very helpful if the example includes angular/jquery promise, as it will give a clear view of practical implementation

推荐答案

关键是使用 ES6 Promise 或实现PromiseLike和PromiseConstructorLike接口的东西/lib/lib.d.ts"rel =" nofollow noreferrer> lib.d.ts (未实现这些接口,因此无法使用.

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.

这是一个使用ES6 Promise的简单示例:

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();

请注意,任何包含await语句的代码都必须位于async函数中,因此我将代码包装为一个.也就是说,即将到来的提案增加了顶级等待",它将在TypeScript 3.8中提供.在此处

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.

这篇关于Async/Await,简单示例(打字稿)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆