美文网首页
JavaScript Async Await

JavaScript Async Await

作者: sean_lau | 来源:发表于2020-04-04 15:28 被阅读0次
    image.png
    image.png
    image.png

    代码:

    function makeRequest(location){
      return new Promise((resolve,reject)=>{
        console.log(`Making Request to ${location}`)
        if(location==='Google'){
          resolve('Google says hi')
        }else{
          reject('we can only talk to Google')
        }
      })
    }
    
    function processRequest(response){
      return new Promise((resolve,reject)=>{
        console.log('processing response')
        resolve(`Extra Information + ${response}`)
      })
    }
    makeRequest('Google').then(response=>{
      console.log('Response Received')
      return processRequest(response)
    }).then(processedResponse=>{
      console.log(processedResponse)
    }).catch(err=>{
      console.log(err)
    })
    
    function makeRequest(location){
      return new Promise((resolve,reject)=>{
        console.log(`Making Request to ${location}`)
        if(location==='Google'){
          resolve('Google says hi')
        }else{
          reject('we can only talk to Google')
        }
      })
    }
    
    function processRequest(response){
      return new Promise((resolve,reject)=>{
        console.log('processing response')
        resolve(`Extra Information + ${response}`)
      })
    }
    // makeRequest('Facebook').then(response=>{
    //   console.log('Response Received')
    //   return processRequest(response)
    // }).then(processedResponse=>{
    //   console.log(processedResponse)
    // }).catch(err=>{
    //   console.log(err)
    // })
    async function doWork(){
      try{
        const response=await makeRequest('Facebook')
        console.log('Response Received')
        const processedResponse=await processRequest(response)
        console.log(processedResponse)
      }catch(err){
        console.log(err)
      }
    }
    doWork()
    

    相关文章

      网友评论

          本文标题:JavaScript Async Await

          本文链接:https://www.haomeiwen.com/subject/emdjphtx.html