异步编程之async/await
- async/await
- async function是Promise的语法糖封装
console.log(async function() {
return 4
}())
console.log(function() {
return new Promise((resolve, reject) => {
resolve(4);
})
}())
(function() {
const result = async function() {
var content = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(6);
}, 500)
})
console.log(content);
return 4;
}()
setTimeout(() => {
console.log(result);
}, 800)
})();
- 异步编程的终极方案 - 以同步的方式写异步
- await关键字可以暂停async function的执行
- await关键字可以以同步的写法获取Promise的执行结果
- try-catch可以获取await所得到的错误
(function() {
const result = async function() {
var content = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve(6);
}, 500)
})
console.log(content);
return 4;
}()
setTimeout(() => {
console.log(result);
}, 800)
})();
await关键字可以把一个Promise的reject抛到一个try catch里面去,前面提到try catch需要依赖调用栈,也就是说它只能够捕捉到调用栈以上的函数所抛出的错误,异步任务创建了一个新的事件循环来执行的代码,在那个地方所抛出的错误try catch是捕捉不到的,但是在使用await之后,这个界线就被打破了,即使这个错误是在异步的回调里面所跑出来了,在经过了await关键字后,这个错误就可以被捕获到了。
(function() {
const result = async function() {
try {
var content = await new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('911'));
}, 500)
})
} catch(e) {
console.log('error111', e.message);
}
console.log(content);
return 4;
}()
setTimeout(() => {
console.log(result);
}, 800)
})();
一个穿越事件循环存在的function
(async function() {
try {
await Promise.all([await interview(1),await interview(2)])
} catch(e) {
return console.log('cry at ' + e.round)
}
console.log('simle');
function interview(round) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.8) {
resolve('success');
} else {
var error = new Error('fail');
error.round = round;
reject(error);
}
}, 500);
});
}
})();
HTTP服务
HTTP是应用层协议
HTTP服务要做什么事情
- 解析进来的HTTP请求报文
- 返回对应的HTTP返回报文
# index.js
const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
console.log(req);
res.writeHead(200);
fs.createReadStream(__dirname + 'index.html')
.pipe(res);
}).listen(3000)
# node index.js
# index.html
<html>
<head></head>
<body>hello geekbang</body>
</html>