1.promise 将程序从异步的执行变成同步的一个过程
比如可以写一个简单的程序来
<script type="text/javascript">
function one(){
return 'I am one'
}
function two(){
//模拟一下网络请求
setTimeout(()=>{
return 'I am two'
},3000)
}
function three(){
return 'I am three'
}
function run(){
console.log(one())
console.log(two())
console.log(three())
}
//调用一下run函数
run()
</script>
此时,打印的结果又由
I am one
I am two
I am three
变成了
I am one
undefined
I am three
是因为two有一个网络请求,但是此时是我没有输出结果的
是因为只有一个run方法,不会等到3秒之后再去执行一次的
要解决这个问题,需要把异步的执行变成同步的
需要改变function two
function two(){
//这是一个标准的promise方法,resolve是一个请求成功返回的,reject是请求失败所要返回的
return new Promise((resolve,reject)=>{
//在这里也是用一个setTimeout去模拟一个网络请求
setTimeout(()=>{
resolve ('I am two‘’)
},3000)
})
}
此时的状态就是
此时的状态 是因为没有声明,要让two执行之后 再去执行three
此时我们要把 run改变一下状态,是要声明里面是有promise请求的
async function run(){
console.log(one())
console.log( await two()) //这个意思就是等two执行完了之后,再去执行three
console.log(three())
}
他的输出结果就是,显示输出
I am one
等三秒之后输出
I am two
I am three