浏览器内置
XMLHttpRequest
直接使用XMLHttpRequest 对象
Pormises
Fetch
generator/yield
async/await
封装、库
jQuery’s $.ajax
Axios and related
大部分应用程序或框架如果不自己实现http 请求,就会使用Axios
Observables
把同步、异步都当作异步的响应式方式
https://my.oschina.net/hyzccc/blog/2994454
Pormise
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises
本质上,Promise 是一个被某些函数传出的对象,我们附加回调函数(callback)使用它,而不是将回调函数传入那些函数内部。
//普通嵌套式处理
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
}, failureCallback);//每层都有失败处理
}, failureCallback);
}, failureCallback);
//Pormise 链式姿势
doSomething().then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);//一遇到异常抛出,Promise 链就会停下来,直接调用链式中的 catch 处理程序
可以链式连缀多个then()
每个then() 均返回Pormise
then() 按先后顺序执行
Fetch
fetch号称是ajax的替代品,它的API是基于Promise设计的
旧版本的浏览器不支持Promise,需要使用polyfill es6-promise
fetch('api/projects').then(response => {
response.json().then(json => {
let data = json;
});
});
//配合Async/Await 食用更佳
let response = await fetch('api/projects');
let data = await response.json();
generator/yield
http://es6.ruanyifeng.com/#docs/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 }