总目录

从C#到TypeScript - async await

上两篇分别说了PromiseGenerator,基础已经打好,现在可以开始讲async await了。

async await是ES7的议案,TypeScript在1.7版本开始支持async await编译到ES6,并在2.1版本支持编译到ES5和ES3,算是全面支持了。

async await 用法

和C#里的十分相似,看个例子:

function delay(): Promise<void>{
return new Promise<void>((resolve, reject)=>{setTimeout(()=>resolve(), 2000)});
} async function run(){
console.info('start');
await delay();
console.info('finish');
} run();
console.info('run');

上面代码执行的结果是执行完run()后立即返回一个Promise,遇到await跳出函数,继续往下走,所以先输出start,再紧接着输出run,过了2秒后再输出finish

可以看到run函数,function前面多了个async(如果是class里的方法,则是在函数名前),delay()前面多了个await,表示的意思很明显,就是在两者之间等待2秒。

run函数返回的也是一个Promise对象,后面可以接then来做后续操作。

await必须要在async块中,await的对象可以是Promise对象也可以不是,不是的话会自动转为已经resolved的Promise对象。

另外,await在代码块中是按顺序执行的,前面wait完后再会走下一步,如果需要并行执行,可以和Promise一样,用Promise.allPromise.race来达到目的。

async function run1(){
await delay();
console.info('run1');
}
async function run2(){
await delay();
console.info('run2');
}
async function run3(){
await delay();
console.info('run3');
}
Promise.all([run1(), run2(), run3()]);

上面代码会在两秒后几乎同时输出run1, run2, run3。

async返回Promise状态

一个async函数中可以有N个await,async函数返回的Promise则是由函数里所有await一起决定,只有所有await的状态都resolved之后,async函数才算真正完成,返回的Promise的状态也变为resolved。

当然如果中间return了或者出了异常还是会中断的。

async function run(){
console.info('start');
await delay();
console.info('time 1');
await delay();
console.info('time 2');
return;
//下面当然就不会执行了
await delay();
console.info('time 3');
}

run的状态在time 2输出后return就转为resolved了。

当这里出异常时,async函数会中断并把异常返回到Promise里的reject函数。

async function run(){
await Promise.reject('error'); // 这里出异常
console.info('continue'); // 不会执行到这里
await delay();
}

异常处理

之前有提到Promise的异常可以在后面用catch来捕获,async await也一样。

向上面的例子,可能有需要把整个函数即使出异常也要执行完,就可以这样做:

async function run(){
await Promise.reject('error').catch(e=>console.info(e));
console.info('continue'); // 继续往下执行
await delay();
} let g = run(); //这里的g也是成功的,因为异常已经被处理掉

如果是多个异常需要处理,可以用try...catch

async function run(){
try{
await Promise.reject('error1');
await Promise.reject('error2');
} catch(e){
console.info(e);
}
console.info('continue'); // 继续往下执行
await delay();
}

async await原理

前篇有说过async await其实是Generator的语法糖。

除了*换成asyncyield换成await之外,最主要是async await内置了执行器,不用像Generator用那样next()一直往下执行。

其实也就是async await内部做了co模块做的事。

先来看看async await在TypeScript翻译后的结果:

async function run(){
await delay();
console.info('run');
}
//翻译成
function run() {
return __awaiter(this, void 0, void 0, function* () {
yield delay();
console.info('run');
});
}

可以注意到其实还是用__await()包了一个Generator函数,__await()的实现其实和上篇的co模块的实现基本一致:

var __awaiter = (this && this.__awaiter) ||
function(thisArg, _arguments, P, generator) {
return new(P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) { // 也是fulfilled,resolved的别名
try {
step(generator.next(value)); // 关键还是这个step,里面递归调用fulfilled
} catch (e) {
reject(e);
}
} function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
} function step(result) {
result.done ? resolve(result.value) : new P(function(resolve) { //P是Promise的类型别名
resolve(result.value);
}).then(fulfilled, rejected); // 没有done的话继续fulfilled
}
step((generator = generator.apply(thisArg, _arguments)).next());
});
};

从C#到TypeScript - async await的更多相关文章

  1. 【TypeScript】如何在TypeScript中使用async/await,让你的代码更像C#。

    [TypeScript]如何在TypeScript中使用async/await,让你的代码更像C#. async/await 提到这个东西,大家应该都很熟悉.最出名的可能就是C#中的,但也有其它语言也 ...

  2. [Typescript] Promise based delay function using async / await

    Learn how to write a promise based delay function and then use it in async await to see how much it ...

  3. [TypeScript] Simplify asynchronous callback functions using async/await

    Learn how to write a promise based delay function and then use it in async await to see how much it ...

  4. [微信小程序] 终于可以愉快的使用 async/await 啦

    [小程序] 终于可以愉快的使用 async/await 啦 这篇文章主要是想说一下 怎么在微信小程序中使用async/await从而逃离回调地狱 背景 最近一直在搞微信小程序 用的语言是TypeScr ...

  5. angular2 学习笔记 ( Rxjs, Promise, Async/Await 的区别 )

    Promise 是 ES 6 Async/Await 是 ES 7 Rxjs 是一个 js 库 在使用 angular 时,你会经常看见这 3 个东西. 它们都和异步编程有关,有些情况下你会觉得用它们 ...

  6. 优雅地 `async/await`

    async/await 虽然取代了回调,使用类似同步的代码组织方式让代码更加简洁美观,但错误处理时需要加 try/catch. 比如下面这样,一个简单的 Node.js 中使用 async/await ...

  7. How Javascript works (Javascript工作原理) (四) 事件循环及异步编程的出现和 5 种更好的 async/await 编程方式

    个人总结: 1.讲解了JS引擎,webAPI与event loop合作的机制. 2.setTimeout是把事件推送给Web API去处理,当时间到了之后才把setTimeout中的事件推入调用栈. ...

  8. JavaScript 如何工作的: 事件循环和异步编程的崛起 + 5 个关于如何使用 async/await 编写更好的技巧

    原文地址:How JavaScript works: Event loop and the rise of Async programming + 5 ways to better coding wi ...

  9. async & await 的前世今生(Updated)

    async 和 await 出现在C# 5.0之后,给并行编程带来了不少的方便,特别是当在MVC中的Action也变成async之后,有点开始什么都是async的味道了.但是这也给我们编程埋下了一些隐 ...

随机推荐

  1. 解决word启动时报找不到mathpage.wll错误

    按下面的网址进行操作即可: http://www.mathtype.cn/wenti/word-jianrong.html

  2. 使用React Native来撰写跨平台的App

    React Native 是一个 JavaScript 的框架,用来撰写实时的.可原生呈现 iOS 和 Android 的应用.其是基于 React的,而 React 是 Facebook 的用于构建 ...

  3. 深入了解Bundle和Map

    [转]http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0402/2684.html 前言 因为往Bundle对象中放入Map实际上 ...

  4. java 对象比较

    class Book{    private String title ;    private double price ; public Book(String title , double pr ...

  5. HTML5学习笔记一:与html4的区别(整合)

    一 语法的改变 1.1 HTML5中标记方法 1.内容类型(ContentType):扩展符仍为“.html”或".htm",内容类型仍是“text/html”. 2.DOCTYP ...

  6. ajax请求获取到数据,但是仍然不能触发success方法

    这个问题消耗了我的很多时间. 原来是因为.php文件中的 echo echo json_encode($k);  后面少加了个exit; 因为echo echo json_encode($k); 之后 ...

  7. dev中TreeList的应用(转)

    如果需要在单元格添加时则用TreeList如果只是单纯读取数据或检索数据时则用GridControl 1.如果点击添加 时则添加TreeList的节点: protected internal void ...

  8. ubuntu下Xmodmap映射Esc和Ctrl_L

    一般来说,用Vim.Emacs的人,都会有做键盘映射的想法 我当然也是,开始学习Vim的时候,就觉得,把Esc键放在左上角, 是一件很SB的事情,稍微大一点的键盘,手指必须要离开位置才能按到Esc键, ...

  9. Php连接及读取和写入mysql数据库的常用代码

    在这里我总结了常用的PHP连接MySQL数据库以及读取写入数据库的方法,希望能够帮到你,当然也是作为我自己的一个回顾总结. 1.为了更好地设置数据连接,一般会将数据连接所涉及的值定义成变量. $mys ...

  10. delphi bitbutton和speedbutton.button有什么区别

    http://zhidao.baidu.com/link?url=LT9_iwv47GfSp3m0MmUSablZrPOxzjKtqWW1yVMTbHnIs2DdCE-0qX2bwXZ2020x_Jl ...