promise 将程序从异步 变成同步

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());
}

上面代码我们发现,two()方法的时候,我们模拟了3秒后执行,则打印的结果为

几分钟搞明白Promise,Async,Await的用法_异步方法

那么,我如果必须要one()走完,然后走two(),再然后走three()呢?

promise就是解决这个问题的!!!!

请看如下代码:

function one(){
return 'I am one'
}

function two(){
return new Promise((resolve,reject)=> {
setTimeout(()=> {
resolve('I am two')
},3000)
})
}

function three(){
return 'I am three'
}

function run(){
console.log(one());
console.log(two());
console.log(three());
}

打印的结果为

几分钟搞明白Promise,Async,Await的用法_异步方法_02

现在的two()已经是个Promise对象啦!

那么,目前为止,还没有达到我们的要求,我们的要求是必须one(),two(),three()分别打印出对应的值!别急,继续往下看:

function one(){
return 'I am one'
}

function two(){
return new Promise((resolve,reject)=> {
setTimeout(()=> {
resolve('I am two')
},3000)
})
}

function three(){
return 'I am three'
}

async function run(){
console.log(one());
console.log(await two());
console.log(three());
}

 

async,await写在对应的异步方法前面,这样,她就等待3秒钟,在继续执行代码啦!同学们自己复制代码运行看看吧~~~

开心~ 今晚总算彻底明白了~~~~~