Appearance
前端发送网络请求
axios
取消请求
// 第一种方式
const CancelToken = axios.CancelToken
const source = CancelToken.source()
axios.get('xxx', {
cancelToken: source.token
})
// 取消请求(请求原因可选)
source.cancel('主动取消请求')
// 第二种方式
const CancelToken = axios.CancelToken
let cancel
axios.get('xxxx', {
cancelToken: new CancelToken(function executor(c) {
cancel = c
})
})
cancel('取消接口避免重复调用')
fetch
fetch('https://www.test.com/', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.ok) {
return response.json()
}
throw new Error('Network response was not ok.')
})
.then(data => console.log(data))
.catch(error => console.error(error))
XHR
// 封装一个ajax请求
function ajax(options) {
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest()
options = options || {}
options.type = (options.type || 'GET').toUpperCase()
options.dataType = options.dataType || 'json'
const params = options.data
// 发送请求
if (options.type === 'GET') {
xhr.open('GET', options.url + '?' + params, true)
xhr.send(null)
} else if (options.type === 'POST') {
xhr.open('POST', options.url, true)
xhr.send(params)
}
// 接收请求
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let status = xhr.status
if (status >= 200 && status < 300) {
options.success && options.success(xhr.responseText, xhr.responseXML)
} else {
options.fail && options.fail(status)
}
}
}
}
使用方式:
ajax({
type: 'post',
dataType: 'json',
data: {},
url: 'https://xxxx',
success: function(text,xml) {
console.log(text)
},
fail: function(status) {
console.log(status)
}
})
promise
Promise就是为了解决回调地狱而产生的,将回调函数的嵌套,改成链式调用。
状态
pending 进行中
fulfilled 已完成
rejected 已失败
实例方法
then()
catch(): 处理错误
finally()
构造函数方法 Promise.all
构造函数方法 Promise.race
async/await
async 使用上更为简洁,将异步代码以同步的形式进行编写,是处理异步编程的最终方案。
const asyncReadFile = async function () {
try {
const f1 = await readFile('/etc/file1');
const f2 = await readFile('/etc/file2');
console.log(f1.toString());
console.log(f2.toString());
} catch(error) {
console.log('try catch 是同步执行的,这里可以捕捉到错误', error)
}
}
Generator
yield 表达式可以暂停函数执行,next方法用于恢复函数执行,这使得 Generator 函数非常适合将异步任务同步化。
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
var hw = helloWorldGenerator()
hw.next()
// { value: 'hello', done: false }
hw.next()
// { value: 'world', done: false }
hw.next()
// { value: 'ending', done: true }
hw.next()
// { value: undefined, done: true