promise应用实例,Promise.all(),Promise.race()
个人应用记录,方便随时copy use
promise应用实例,Promise.all(),Promise.race()
const repos = [ {name: 'grit', owner: 'mojombo', description: 'Grit 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: 'mojombo', location: 'San Francisco', followers: 123}, {name: 'vanpelt', location: 'Bay Minette', followers: 1034}, {name: 'wycats', location: 'Los Angeles, CA', followers: 388} ] function getReposInfo(ids){ return new Promise((resolve,reject) => { const reposVal = repos.find(vals => vals.id == ids) if(reposVal){ resolve(reposVal) }else{ reject(Error('no fond')) } }) } function getOwnersInfo(infos){ return new Promise((resolve,reject) => { const getInfo = owners.find(vals => vals.name == infos.owner) if(getInfo){ infos.owners = getInfo resolve(infos) }else{ reject(Error('Not fond this name')) } }) } getReposInfo(1) .then(res => { return getOwnersInfo(res) } ) .then(res => { console.log(res) }) .catch(res => { console.error('res') })
//多个Promise回调方法 function getReposInfo(ids){ return new Promise((resolve,reject) => { const reposVal = repos.find(vals => vals.id == ids) if(reposVal){ resolve(reposVal) }else{ reject(Error('no fond')) } }) } function getOwnersInfo(infos){ return new Promise((resolve,reject) => { const getInfo = owners.find(vals => vals.name == infos.owner) if(getInfo){ infos.owners = getInfo resolve(infos) }else{ reject(Error('Not fond this name')) } }) } const one = new Promise((resolve,reject) => { resolve(['1','2']) }) const two = new Promise((resolve,reject) => { resolve({name:'ted',age:'19'}) }) Promise // .all([one,two]) //等待所有Promise resolve后执行then,否则catch .race([one,two]) //第一个响应resolve就进入then。或者第一个reject就直接进入catch。 .then(response => { const [a,b] = response console.log(a) console.log(b) }) .catch(response => { console.error(response) })