Skip to content

Latest commit

 

History

History
102 lines (90 loc) · 3.01 KB

14.promise-intro.md

File metadata and controls

102 lines (90 loc) · 3.01 KB

Promis

回调函数真正的问题在于他剥夺了我们使用 return 和 throw 这些关键字的能力。而 Promise 很好地解决了这一切。

const usersApi = 'https://api.github.com/users';
const usersPromise = axios.get(usersApi);
let username;
usersPromise
    .then(response => {
        username = response.data[0].login;
        const userApi = `https://api.github.com/users/${username}/repos`;
        return axios.get(userApi);
    })
    .then(response => console.log(response))
    .catch(error => console.log(error));

自定义promise

const p = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('成功返回');
        //reject(Error('失败返回));
    }, 2000);
});

p.then(data => console.log(data)).catch(error => console.error(error));

实例应用

const repos = [
    { name: 'grit', owner: 'mojobo', description: 'Grist is no longer maintained', id: 1 },
    { name: 'jsawesome', owner: 'vanpelt', description: 'Awesome JSON', id: 2 },
    { name: 'merb-core', owner: 'wycats', description: 'Merb Core:All you need.None you don\'t', id: 3 }
];

const owners = [
    { name: 'mojobo', location: 'San Francisco', followers: 123 },
    { name: 'vanpelt', location: 'Bay Minette', followers: 1034 },
    { name: 'wycats', location: 'Los Angeles, CA', followers: 388 },
];

function getReposById(id = 1) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const repo = repos.find(repo => repo.id === id);
            if (repo) {
                resolve(repo);
            } else {
                reject(Error('No repo matched'));
            }
        }, 2000);
    });
}

function combineOwner(repo) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const owner = owners.find(owner => owner.name === repo.owner);
            console.log(owner);
            if (owner) {
                repo.owner = owner;
                resolve(repo);
            } else {
                reject(Error('Owner not found'));
            }
        }, 2000);
    });
}

getReposById()
    .then(repo => combineOwner(repo))
    .then(repo => console.log(repo))
    .catch(err => console.error(err));

处理多个Promise

const usersPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(['mojombo', 'vanpelt', 'wycats']);
        
    }, 2000);
});

const moviePromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve({ name: '摔跤吧爸爸', rating: 9.2, year: 2016 });
        // reject(Error('No movies'));
    }, 500);
})

// 如果调用 all 方法,返回结果为数组,结果顺序按照 all 方法数组参数顺序排列,如果返回结果有一个为失败,则会是失败状态,会执行 catch 里面的方法
// 如果调用 race 方法,状态由最先 promise 返回的状态决定
Promise
    .race([usersPromise, moviePromise])
    .then(response => {
        console.log(response);
    })
    .catch(error => console.error(error));