对于ES6 promise和ES7 async、await的理解

promise ES6提出

用于解决异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。

new Promise((resolve, reject) => {
    $ajax({
        url: _url,
        success:function(ret) {
            // 成功回调
            resolve(ret);
        },
        error: function(err) {
            // 失败回调
            reject(err)
        }
    });
}).then(ret => {
    // 处理成功数据
    // code ......
}).catch(err => {
    // 错误处理
    // code ......
})

这样完美解决了ajax的回调地狱问题。

async、await ES7提出

优化ES6异步编程的解决方案,比ES6 Promise更加优美。

function async(_url) {
    return new Promise((resolve, reject) => {
        $ajax({
            url: _url,
            success:function(ret) {
                // 成功回调
                resolve(ret);
            },
            error: function(err) {
                // 失败回调
                reject(err)
            }
        });
    });
}

async function fetchData() {
    const ret = await async('/api/getList');
}

// 使用
fetchData();

注意:
1、async 会返回一个Promise对象,并且是resolved状态,这意味着这个对象状态不可再改变(不了解请看我的Promise学习笔记)。
2、await 它会等待后面的表达式或者Promise对象执行完成才会执行后面的语句(仅限于await对应的函数中)。
3、await 它可以等任意表达式的结果。
4、如果它等到的不是一个 Promise 对象,那 await 表达式的运算结果就是它等到的东西,并且不会阻塞后面的代码运行。
5、如果它等到的是一个 Promise 对象,await 就忙起来了,它会阻塞后面的代码,等着 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果。
6、await必须放在async函数中。

总结:Promise解决了异步回调地狱问题,而async、await是对Promise的升华,进一步提升了Promise的强大。

下面给点干货自己去体会

1、有层次的发起请求

let status = 1;
let userLogin = (resolve, reject) => {
    setTimeout(() => {
        if (status == 1) {
            resolve({
                data: '登录',
                msg: 'xxx',
                token: 'xxx'
            });
        } else {
            reject('请求失败');
        }
    }, 2000);
}

let userInfo = (resolve, reject) => {
    setTimeout(() => {
        if (status == 1) {
            resolve({
                data: '用户信息',
                msg: 'xxx',
                token: 'xxx'
            });
        } else {
            reject('请求失败');
        }
    }, 2000);
}

new Promise(userLogin).then(res => {
    console.log(res); // 登录成功
    return new Promise(userInfo); // 登录成功后再请求获取用户信息
}).then(ret => {
    console.log(ret); // 得到用户信息
})

2、对于Promise的理解

async function test() {
    console.log('1');
    await new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('2')
            resolve();
        }, 1000);
    })
    console.log('3');
}

test();
console.log('4');

// 1、4、2、3

3、最近很火的一道面试题

async function async1() {
    console.log('async1 start')
    await async2()
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
}
console.log('script start')
setTimeout(function () {
    console.log('setTimeout')
}, 0)
async1();
new Promise(function (resolve) {
    console.log('promise1')
    resolve();
}).then(function () {
    console.log('promise2')
})
console.log('script end')

// script start
// async1 start
// async2
// promise1
// script end
// async1 end
// promise2
// setTimeout

4、对于async函数的理解

async function testAsync() {
    return "hello async";
}

const result = testAsync();
console.log(result);    // Promise {: "hello async"}

5、对于async和await的理解

function takeLongTime() {
    return new Promise(resolve => {
        return setTimeout(() => resolve("long_time_value"), 1000);
    });
}

async function test() {
    console.log('1');
    const v = await takeLongTime();
    console.log(v);
    console.log('2');
}

test(); // 1、long_time_value、2

6、区别async和Promise

async function async() {}

const async1 = new Promise((resolve,reject) => {})

console.log(async());   // Promise {: undefined}
console.log(async1);    // Promise {}

注意:async返回的Promise对象已经是resolved状态

你可能感兴趣的:(对于ES6 promise和ES7 async、await的理解)