promise是构造函数
setInterval(() => {
const n = Math.random()
new Promise((resolve,reject) => {
if (n < 0.5) {
resolve(n)
} else {
reject('cuowule')
}
}).then( (data) => {
console.log(data)
}).catch( mes => {
console.log(mes)
})
}, 3000);
promise封装
function request1 (url,cb) {
return new Promise((resolve, reject) => {
var xml = new XMLHttpRequest()
xml.addEventListener('load', function () {
resolve(this.responseText)
})
xml.open('get', url)
xml.send()
})
}
request1('http://jsonplaceholder.typicode.com/posts').then(function (data) {
console.log(data)
})
- async await
await就是等待,等待await后面的函数执行完毕,异步函数内部再往下执行
function request1 (url) {
return new Promise((resolve, reject) => {
var xml = new XMLHttpRequest()
xml.addEventListener('load', function () {
resolve(this.responseText)
})
xml.open('get', url)
xml.send()
})
}
async function getData () {
const a = await request1('http://jsonplaceholder.typicode.com/posts')
console.log(a,111)
const b = await request1('http://jsonplaceholder.typicode.com/posts')
console.log(b, 222)
const c = await request1('http://jsonplaceholder.typicode.com/posts')
console.log(c, 333)
}
getData()
// 111 222 333