天天看點

幾分鐘搞明白Promise,Async,Await的用法

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的用法

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

      

繼續閱讀