Async / Await 问题

Async/Await 的实践

首先简单总结, Async和Await 能够将异步操做像写同步操做那样简单promise

注意: await 所等待的函数必须返回对象为Promise,若是不是 须要 return new promise 才能够异步

 let promise = new Promise((resolve, reject) => {
  // 异步函数执行成功时执行回调,若resolve函数有带参数,则该参数会传递给回调函数
  resolve()
  // 异步函数执行失败时执行回调,若reject函数有带参数,则该参数会传递给回调函数
  reject()
 })
 
 function setTime(time) {
     return new Promise((reslove)=>{
         setTimeout(() => {
             console.log(time)
             reslove() // 自执行成功函数
        }, time);
    })
 }
 
 function setTime(time) {
     return new Promise((res)=>{
         setTimeout(() => {
             console.log(time)
             res()
        }, time);
    })
 }
 
 let main = async function() {
     await setTime(100)
     console.log('执行到1')
     await setTime(1000)
     console.log('执行到2')
 }
 main()

这样整个程序就能够将异步按照同步的方法去运行了async

 

 

注意,必定要把须要回传的参数放在reslove中,若是没有 也要把reslove 执行一下,否则Promise会被中断,以下函数

相关文章
相关标签/搜索