Promise是为了AJAX请求变得更加优雅,Promise并不能发送请求,是为了解决回调地狱。
Promise主要是为了解决js中多个异步回调难以维护和控制的问题。
在ES6中,Promise对象是一个构造函数,用来生成promise实例。
Promise构造函数,接收一个函数作为参数,该函数有两个参数,分别是resolve,reject(这两个是函数,由js引擎提供,不用自己部署)
Promise实例生成以后,可以用then方法分别指定resolved,rejected状态的回调函数。
then方法接受两个回调函数作为参数:
1.Promise对象变成resolved时调用,
2.Promise对象变成rejected时调用。
ajax结合promise发送网络请求
var getData=function(url,type,data){
var promise=new Promise(function(resolve,reject){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open(type,url);
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState!==4){
return;
}else{
if(xmlhttp.status>=200&&xmlhttp.status<300 || xmlhttp.status===304){
resolve(xmlhttp.responseText);
}else{
reject(new Error(xml.xmlhttp));
}
}
}
if(type=='get'){
xmlhttp.send();
}else{
xmlhttp.setRequestHeader("Content-Type","application/json");
xmlhttp.send(JSON.stringify(data));
}
});
return promise;
}
Promise串行
一个异步请求完了之后再进行下一个请求
queryThen(){
getData('/get1','get')
.then(res=>{
console.log(res);
return getData('/get2','get');
},err=>{
console.log(err);
})
.then(res=>{
console.log(res);
},err=>{
console.log(err);
})
}
Promise并行
多个异步请求同时进行,这些异步请求都成功了之后才会返回结果,其中任何一个没有成功,都拿不到结果。
Promise.all([
getData('/get1','get')
.then(res=>{console.log(res)}),
getData('/get2','get')
.then(res=>{console.log(res)})
])
var p1=new Promise(function(resolve,reject){
getData('/get1','get')
.then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
});
var p2=new Promise(function(resolve,reject){
getData('/get2','get')
.then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
});
promise.all([p1,p2])
.then(([res1,res2])=>{
console.log(res1,res2);
})
Generator函数
Generator函数是ES6提供的一种异步编程解决方案。
Generator函数的调用方法和普通函数一样,也是在函数后面加上一对圆括号。不同的是,调用该函数后,该函数并不执行, 返回的也不是函数运行的结果,而是一个指向内部状态的指针变量,也就是迭代器对象。
下一步,必须调用迭代器对象的next方法,使得指针移向下一个状态。
形式上,Generator函数是一个普通函数,是分段执行的,yield表达式是暂停执行的标记,而next方法可以恢复执行。
有两个特征:
1.function关键字与函数名之间有一个星号。
2.函数体内部使用yield表达式,定义不同的内部状态。
ES6没有规定,function关键字与函数名之间的星号,写在哪个位置,都正确。
yield表达式
yield表达式是暂停执行的标记。
yield表达式后面的表达式,只有当调用next方法,内部指针指向该语句时才会执行。
yiled表达式本身没有返回值,或者说总是返回undefined。
yield表达式与return的相似之处
都能返回紧跟在语句后面的那个表达式的值。
yield表达式与return的不同之处
1.每次遇到yield,函数暂停执行,下一次再从该位置继续向后执行,而return函数不具有位置记忆功能。
2.一个函数里面,只能执行一次return语句,而可以执行多个yield表达式;Generator函数可以返回一系列的值,因为可以有任意多个yield。
注意
1.Generator函数可以不用yield表达式,就变成了一个单纯的暂缓执行函数。
2.yield表达式只能用在Generator函数里面,用在其他地方会报错。
3.yield表达式如果在另一个表达式里面,要用括号括起来。
4.yield表达式用作函数的参数或者放在赋值表达式的右边,可以不加括号。
next方法
遍历器对象的next方法运行逻辑如下:
1.遇到yield表达式,就暂停后面的操作,并且将紧跟在yield表达式后面的那个表达式的值,作为返回的对象的value属性值。
2.下一次调用next方法时,再继续往下执行,知道遇到下一个yield表达式。
3.如果没有再遇到新的yield表达式,就一直运行到函数结束,直到return语句为止,并将return语句后面的表达式的值,作为返回的对象的value属性值。
4.如果该函数没有return语句,则返回的对象的value属性值为undefined。
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 }
next方法的参数
yield表达式本身没有返回值,或者说总是返回undefined。
next方法可以带一个参数,该参数就会被当做上一个yield表达式的返回值。
function* foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var a = foo(5);
a.next() // Object{value:6, done:false}
a.next() // Object{value:NaN, done:false}
a.next() // Object{value:NaN, done:true}
var b = foo(5);
b.next() // { value:6, done:false }
b.next(12) // { value:8, done:false }
b.next(13) // { value:42, done:true }
由于next方法参数表示的是上一个yield表达式的返回值,所以在第一次使用next方法时,传递参数是无效的。
generator和Promise一起使用
function * bar(){
console.log("111");
const result=yield new Promise((resolve,reject)=>{
setTimeout(() => {
resolve("hello generator");
}, 3000);
});
console.log(result);
}
const it=bar();
it.next().value.then(res=>{ // 111
it.next(res); // hello generator
});
for…of循环
可以自动遍历Generator函数运行时生成的Iterator对象,且此时不再需要调用next方法。
一旦next方法的返回对象的done属性为true,for…of循环就会中止,且不包含该返回对象。
yield* 表达式
yield* 表达式,用来在一个Generator函数里面执行另一个Generator函数。
实际上,任何数据结构只要有Iterator接口,就可以被yield*遍历。
Generator函数的this
Generator函数总是返回一个遍历器,ES6规定这个遍历器是Generator函数的实例,也继承了Generator函数的prototype对象上的方法。
function * g(){}
g.prototype.hello=function(){
return 'hi';
}
let obj=g();
obj instanceof g // true
obj.hello() // 'hi'
Generator函数g返回的遍历器obj,是g的实例,而且继承了g.prototype。
但是如果把g当成普通的构造函数,并不会生效,因为g返回的总是遍历器对象,而不是this对象。
function * g(){
this.name='mm';
}
let obj=g();
obj.a // undefined
Generator函数也不能跟new命令一起用,会报错。
什么方法可以让Generator函数返回一个正常的对象实例,既可以用next方法,有可以获得正常的this呢?
首先生成一个空对象,使用call方法绑定Generator函数内部的this。这样,构造函数调用以后,这个空对象就是Generator函数的实例对象了。
function * F(){
this.a=1;
yield this.b=2;
yield this.c=3;
}
var obj={};
var f=F.call(obj);
f.next(); // Object {value: 2, done: false}
f.next(); // Object {value: 3, done: false}
f.next(); // Object {value: undefined, done: true}
obj.a // 1
obj.b // 2
obj.c // 3
但是执行的是遍历器对象f,生成的对象实例是obj,如何将这两个对象统一呢?
一个办法就是将obj换成F.prototype。
function* F() {
this.a = 1;
yield this.b = 2;
yield this.c = 3;
}
var f = F.call(F.prototype);
f.next(); // Object {value: 2, done: false}
f.next(); // Object {value: 3, done: false}
f.next(); // Object {value: undefined, done: true}
f.a // 1
f.b // 2
f.c // 3
再将F改成构造函数,就可以对它执行new命令了。
function* gen() {
this.a = 1;
yield this.b = 2;
yield this.c = 3;
}
function F() {
return gen.call(gen.prototype);
}
var f = new F();
f.next(); // Object {value: 2, done: false}
f.next(); // Object {value: 3, done: false}
f.next(); // Object {value: undefined, done: true}
f.a // 1
f.b // 2
f.c // 3
实现斐波那契数列
function * fibonacci(){
let [prev,cur]=[0,1];
for(;;){
yield cur;
[prev,cur]=[cur,prev+cur];
}
}
for(let n of fibonacci()){
if(n>1000) break;
console.log(n);
}
生成器函数实例
1s后控制台输出111,2s后控制台输出222,3s后控制台输出333
setTimeout(()=>{
console.log(111);
setTimeout(()=>{
console.log(222);
setTimeout(()=>{
console.log(333);
},3000)
},2000)
},1000)
function one(){
setTimeout(()=>{
console.log(111);
},1000)
}
function two(){
setTimeout(()=>{
console.log(222);
},2000)
}
function three(){
setTimeout(()=>{
console.log(333);
},3000)
}
function *gen(){
yield one();
yield two();
yield three();
}
let iterator = gen();
iterator.next();
iterator.next();
iterator.next();
async函数
async函数是什么,它就是Generator函数的语法糖。
async函数对Generator函数的改进,有以下4点:
1.内置执行
Generator函数的执行需要调用next方法,或者用co模块。(co模块???)
async函数自带执行器,也就是说,async函数的执行,与普通函数一样,只要一行。
2.更好的语义
async表示函数里面有异步操作,
awiat表示紧跟在后面的表达式需要等待结果。
3.更广的适用性
async函数的await命令后面,可以是Promise对象和原始类型的值(数值、字符串和布尔值,但是这时会自动转成立即resolved的Promise对象),
如果返回结果是一个promise对象,
return new Promise((resolve,reject)=>{resolve('成功的数据');reject('失败的错误')});
那么函数的返回结果取决于Promise的状态;
如果返回的结果不是promise类型的对象,那么函数的返回结果是成功的promise,resolve;async函数内部return 语句返回的值,会成为then方法回调函数的参数。
如果抛出错误,那么函数的返回结果是失败的Promise,reject。
4.返回值是Promise
Generator函数的返回值是Iterator对象,
async函数的返回值是Promise对象,可以用then方法指定下一步的操作。
async函数完全可以看成多个异步操作,包装成一个promise对象,而await命令就是内部then命令的语法糖。
async function f(){
return 'abc';
}
f().then(res=>{
console.log(res);
})
console.log('xyz');
// xyz
// abc
await
用于等待一个Promise对象,它只能在异步函数async function内部使用。
语法:await 一个promise对象或者任何要等待的值。
console.log(1);
async function f(){
console.log(2);
}
f();
console.log('xyz');
// 1
// 2
// xyz
console.log(1);
async function f(){
console.log(2);
await 100; // 阻塞
console.log(3); // 异步任务
}
f();
console.log('xyz');
// 1
// 2
// xyz
// 3
应用
async function f(){
await getData('/get1','get');
await getData('/get2','get');
}
宏任务和微任务
setTimeout(()=>{
console.log(1); // 宏任务
},0)
new Promise(function(resolve,reject){
resolve();
console.log(2);
}).then(function(){
console.log(3); // 微任务
});
console.log(4);
// 2
// 4
// 3
// 1
function p(){
return new Promise(resolve=>{
setTimeout(()=>{
resolve();
console.log('abc');
},1000)
});
}
async function f(){
console.log(2);
await p(); // 异步同步化
console.log(3);
}
f();
// 2
// abc 1s后执行
// 3
宏任务
setTimeout
微任务
Promise
then
async