一、async-await【ES8】
- 异步操作又一种解决方案
- async-await一般是成对出现的
- async写在function前面
1. 用法示例
function timeout() {
return new Promise(resolve => {
setTimeout( ()=> {
console.log(1)
resolve()
}, 1000)
})
}
async function foo() {
await timeout()
console.log(2)
}
foo()
function ajax(url, callBack) {
var xmlhttp
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest()
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
}
xmlhttp.open('GET', url, true)
xmlhttp.send()
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var obj = JSON.parse(xmlhttp.responseText)
callBack(obj)
}
}
}
function request(url) {
return new Promise(resolve => {
ajax(url, res => {
resolve(res)
})
})
}
async function getData() {
let res1 = await request('xxxa')
let res2 = await request('xxxb')
let res3 = await request('xxxc')
}