未加星标

Async-await to the rescue!

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

TC39 (committee responsible for ECMAScript) conservatism in adding new semantics and syntax is pretty well known. ES5 came out in 2009 and the next large version called ECMAScript 2015 (formerly: ES6) was released in 2015. You could expect that after six years the changes in the language would be revolutionary. And in some sense they are, since javascript has never gone through so many changes. Yet in comparison to python release cycle you could say those changes are cosmetic at best.

Solutions such as Promises or generators are good foundation for most applications. You can implement any control flow with them.

What generators actually are

Considering the theory of programming, generators are a particular case of coroutines. In theory a coroutine is a procedure (or function, or method) that retains its execution state between consecutive calls.

Consider the following code:

function* ourGenerator(){
for(var i = 0; i < 5; i++) yield i;
}
const gen = ourGenerator();
gen.next(); // {done: false, value: 0}
gen.next(); // {done: false, value: 1}

gen.next(); // {done: true}

As you can see, the next step could be executed at any time. Furthermore, the generators allow to send messages back to the code:

function* ourGenerator(){
for(var i = 0; i < 5; i++) i = yield i;
}
let gen = ourGenerator();
gen.next(); // {done: 0, value: 0}
gen.next(); // {done: false, value: undefined}
gen.next(); // {done: true}
gen = ourGenerator();
gen.next();
gen.next(3); // {done: false, value: 4}
gen.next(3); // {done: false, value: 4}

The value of expression yield…” is being replaced by the first argument of the following execution of the next() method. What would happen if Promise became the result of the expression? Can we use this functionality to write asynchronous code that looks synchronous?

My first thought is to yield Promise from the generator and send back the actual data. Something like this:

const users = {get: email=>Promise.resolve({name: ‘Foo Bar’, email: email}));
function getUser() {
const user = wait for users.get(‘[email protected]’);
console.log(user); // {name: ‘Foo Bar’, ‘email’: ‘[email protected]’}
}

That functionality, but inspired by similar C# async-await syntax, is a proposition to ECMAScript 2017 . It is now on development stage 3 of 5.

async function getUser(){
const user = await users.get(‘[email protected]’);
console.log(user);
}

Async-await is a breakthrough in the world of JavaScript. Promises freed us from nesting callbacks indefinitely (so called callback hell). Async-await goes one step further, because synchronous and asynchronous codes are basically indistinguishable.

async function throwCatch() {
try {
await Promise.reject(new TypeError(‘throwed’));
} catch(e) {
console.log(e); // TypeError: throwed
}
}

Simplicity and clarity of this model is evident to any imperative language programmer. I will show you how to download files orderly using Fetch API :

function fetchAll(urls=[]) {
const ret = {};
for(const url of urls) { ret[url] = await fetch(url); }
return ret;
}

It’s extremely easy to move from doing things orderly to concurrent downloads:

for(const {url,promise} of urls.map(url=>({url, promise: fetch(url)})) { ret[url] = await promise; } Async-await lets you avoid using antipatterns

It is a truth universally acknowledged, that every developer sometimes makes mistakes. From simple errors such as typos, up to using antipatterns. One of the most popular antipatterns is using new Promise. All too often we see code looking like this:

return new Promise((resolve, reject) => {
$http.get(‘url’) .then(data=>resolve(data)) .catch(err=>reject(err));
});

Nesting long closures into asynchronous function stands out a lot. You can clearly see that something is terribly wrong here:

async function fooBar() {
new Promise((resolve, reject) => { $http.get(‘url’) .then(data=>resolve(data)) .catch(err=>reject(err));
});
}

What the programmer needs is this:

Promise.resolve($http.get(‘url’)); // Async-await solves different problems than Promises do

Promises are, in principle, monad-like. They wrap the value that will be available in the future and enable using it the moment it becomes accesible. Conceptually speaking, they are based on and limited to value passing. Using Promises to execute asynchronous code is, in fact, abusing them.

Async-await is too much of a bleeding edge for my company/my boss

You poor thing ;_; We have no such restrictions in our company. In this case though, I would recommend using the fantastic Bluebird library and the function Promise.coroutine .

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: ECMAScriptJavaScriptJavaC#Python
分页:12
转载请注明
本文标题:Async-await to the rescue!
本站链接:http://www.codesec.net/view/482581.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(22)