赵鑫20200925
学习总结
pormise
异步之间传参
function hello(){
var text='你好,我是saoge';
setTimeout(function(){
console.log(text);
say(text);
},1000)
}
function say(text){
setTimeout(function(){
console.log(text)
},1000)
}
hello();
Promise在执行成功的时候,会调用resolve,因此,我们就可以用resolve来传值。
var pro = new Promise((resolve, reject) => {
setTimeout(function() {
var text = '你好,我是saoge';
console.log(text);
resolve(text);
}, 1000)
})
pro.then(function(data) {
setTimeout(function() {
console.log(data);
}, 1000)
})
需要等待多个函数执行完毕再执行时:Promise.all()
function helloOne() {
return new Promise(
function(next) {
setTimeout(function() {
console.log('你好,我是saoge');
next();
}, 1000)
})
}
function helloTwo() {
return new Promise(
function(next) {
setTimeout(function() {
console.log('你好,很高兴认识你');
next();
}, 2000)
})
}
function helloThree() {
return new Promise(
function(next) {
setTimeout(function() {
console.log('交个朋友吧');
next();
}, 3000)
})
}
Promise.all([helloOne(),helloTwo(),helloThree()]).then(function(){
setTimeout(function(){
console.log('可以吗?')
},1000)
});
上面这段代码就会先在一秒钟我说出你好,我是骚哥。然后再过一秒钟我说你好,很高兴认识你。再过一秒钟说出交个朋友吧,我们可以看到在then()方法里面有一个函数,是一秒钟之后询问你可以吗?而这句话执行的时间是第四秒。也就是Promise.all中的函数执行完成之后再去执行hten()方法中的语句。
Promise.race()
function helloOne() {
return new Promise(
function(next) {
setTimeout(function() {
console.log('你好,我是saoge');
next();
}, 1000)
})
}
function helloTwo() {
return new Promise(
function(next) {
setTimeout(function() {
console.log('你好,很高兴认识你');
next();
}, 2000)
})
}
function helloThree() {
return new Promise(
function(next) {
setTimeout(function() {
console.log('交个朋友吧');
next();
}, 3000)
})
}
Promise.race([helloOne(),helloTwo(),helloThree()]).then(function(){
setTimeout(function(){
console.log('可以吗?')
},1000)
});
看上面这个例子,执行一秒之后输出“你好,我是骚哥”,然后再过一秒钟会输出两句话,“你好,很高兴认识你”,“可以吗?”,最后再输出“交个朋友吧” 可以看出,在helloOne执行完毕之后,then()中的代码就开始执行了,和Promise.all()的不同就在于,只要有一个执行成功就去执行hten()中的代码。
async
1.async干了什么
async function helloOne(){
setTimeout(function(){
return("你好,我是骚哥");
},1000)
}
console.log(helloOne()) //Promise {<fulfilled>: undefined}
async 返回的是一个Promise对象。
async function helloOne(){
setTimeout(function(){
return("你好,我是骚哥");
},1000)
}
console.log(helloOne()); //Promise {<fulfilled>: undefined}
helloOne().then(function(data){
console.log(data) //undefined
})
我们尝试用then()去获取async函数中的值,但是返回的是undefined,且两个输出语句是同时执行的,所以说then()中的函数还没有等到异步函数执行完便执行了,因此这里和Promise不太一样。
function helloOne() {
return new Promise((resolve,reject)=>{
setTimeout(
function(){
resolve( '你好,我是saoge');
}, 1000)
});
}
function helloTwo(){
setTimeout(
function(){
return '拜拜';
}, 1000)
}
async function say(){
var one = await helloOne()
console.log(one) //你好,我是saoge
var two = await helloTwo()
console.log(two) //undefined
}
say()
直接看代码,可以发现,如果await 后面跟的是一个Promise对象,那么将会等到Promise对象resolve,然后将resolve的值作为表达式的结果。如果不是以恶搞promise对象,那么await的运算结果就是此时传入的东西,兵不会有其他作用。
学习心得
多总结多记忆,然后就是我觉得如果是理解性没有那么强的知识,老师可以讲快点,毕竟课堂时间是宝贵的,遇到问题了做项目的时候再探究。
近期评论