背景 #
在JavaScript的世界中,所有代码都是单线程执行的。由于这个“缺陷”,导致JavaScript的所有网络操作,浏览器事件,都必须是异步执行。假设有这么一个场景,在一个电商系统中,需要根据userId查询到用户购买的商品信息,其步骤如下:
- 查询用户服务,根据userId查询到用户信息(orderId)
- 查询订单服务,根据orderId查询到订单信息(productId)
- 查询商品服务,根据productId查询到商品信息
在ES6之前,我们只能使用回调函数来实现这个功能,其代码示例如下:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.com/user', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();