异步中的回调与promise

in JavaScript with 0 comment

javascript 异步中的回调与promise

     /*
     //函数中使用异步返回的结果方法一:使用回调函数
     function getSomething(cb) {
       let r = 0
       setTimeout(() => {
         r = 2
         cb(r)
       },1000)
       return r
     }
     function compute(x) {
       console.log(x * 2)
     }
     getSomething(compute)
     */
     
     /*
     //函数中使用异步返回的结果方法二:使用promise
     function getSomething() {
       let r = 10
       return new Promise((resolve, reject) => {
          setTimeout(() => {
            r = 30
            resolve(r)
          },1000)
        })
     }
     function compute(x) {
       console.log(x * 2)
     }
     //promise.then()会调用里边的回调函数,这个回调函数就是compute
     getSomething().then(compute)
    //  getSomething().then((val) => {
    //    console.log(val * 2)
    //  })
    */
     
    /*
    //函数中使用异步返回的结果方法三:使用 generator
    function getSomehing() {
      let r = 0
      setTimeout(() => {
        r = 20
        it.next(r) 
      },2000)
    }
    function *compute(it) {
      let x = yield getSomehing()
      console.log(x * 2)
    }
    let it = compute()
    it.next()
*/
   //函数中使用异步返回的结果方法四:大招:使用 async/await结合promise
    function getSomething(){
      let r = 0
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          r = 20
          resolve(r)
        }, 2000)
      })
    }
    async function compute(){
      const res = await getSomething()
      console.log(res * 2)
    }
    compute()
评论已关闭.