# ES6 语法

参考 ES6 (opens new window) 文档,列出常用ES6方法

# Promise 用法

该部分主要介绍 Promise (opens new window) 的常用用法

# 基础用法

function listUser(query) {
    return new Promise((resolve, reject) => {
        request({
            url: 'xxx',
            method: 'get',
            params: query
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

# Promise.all()用法

Promise.all() (opens new window),等待所有Promise完成才会执行 then ,否则 catch

// 生成一个Promise对象的数组
const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
    return getJSON('/post/' + id + ".json");
});

Promise.all(promises).then(function (posts) {
    // ...
}).catch(function (reason) {
    // ...
});

# Promise.race()用法

Promise.race() (opens new window),等待首个Promise完成才会执行 then ,否则 catch

const p = Promise.race([
    fetch('/resource-that-may-take-a-while'),
    new Promise(function (resolve, reject) {
        setTimeout(() => reject(new Error('request timeout')), 5000)
    })
]);

p.then(console.log).catch(console.error);