promise-async-await

通常而言,这3个关键字 都是用来「优雅」的处理ajax异步请求的

     //es6的时候promise诞生,很好的解决了嵌套回调地狱,改良方案为链式回调。
    // es2017的时候诞生了async、await,这下异步直接没有回调了,像同步一样爽

    //没有promise的时候
    $('button').click(()=>{
        let url='http://t.weather.sojson.com/api/weather/city/101010100';
        $.get(url,(res)=>{
            console.log(res)
        })
    })


    //有promise的时候(jq内部ajax增加了返回promise格式,之前不支持,只能嵌套回调)
    $('button').click(()=>{
        let url='http://t.weather.sojson.com/api/weather/city/101010100';
        $.get(url).then((res)=>{
            console.log(res)
        })
    })

    //有await时代(async只能用在返回promise代码中,将其包裹,表明我这里边异步。  用await表示 等一下我的异步 执行完再向下执行)
    $('button').click(async ()=>{
        let url='http://t.weather.sojson.com/api/weather/city/101010100';
        let res=await $.get(url)
        console.log(res)
    })

另外推荐优质博客:
https://blog.csdn.net/yanh_an
http://www.fromyan.com/

或百度搜索:YanH_an



原文地址:https://www.cnblogs.com/dshvv/p/9982114.html