In JavaScript, all code is single-threaded execution.
1. Test whether the browser supports Promise
'use strict';
new Promise(function(){});
console.log ( 'Support Promise!');
2.
<-! Axios is based on the promise of a HTTP library, you can use the browser 和node.js中 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"> </script> <script> let username; const usersPromise=axios.get('https://api.github.com/users') // 监听事件 usersPromise.then(reponse=>{ // console.log(reponse); username=reponse.data[0].login; // 返回promise return axios.get(`https://api.github.com/users/${username}/repos`); }).then(reponse=>{ console.log(reponse.data); }) // listens error occurs the catch . The catch (ERR => { console.error(err) }) </script>
reponse data inside
3. Practice Code
(1) promise success stories reslove (to change the parameter name)
// reslove incoming data successful // if it fails to return to reject information const = the p- new new Promise ((reslove, reject) => { setTimeout(()=>{ reslove('This is successful') },2000); }) p.then (Data => { // successful information console.log (data); })
(2) promise failures reject (to change the parameter name)
// reslove incoming data successful // if it fails to return to reject information const = the p- new new Promise ((reslove, reject) => { setTimeout(()=>{ reject('This is successful') },2000); }) p.then(data=>{ console.log(data); .}) The catch (ERR => { // failure information console.error (err); })
4. promise of using a plurality of
Promise.all (iterable) method returns an instance Promise
All are within iterable parameter promise success callback is completed, if there is a failed promise parameters so the callback instance failure. Failure to find catch inside the code
Promise.race (iterable) method returns a promise, once the iterator a promise to solve or refuse to return to the promise will be resolved or rejected. Note that the timer time: tip.
const usersPromise=new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(['mojombo','vanpelt','wycats']);
},2000);
});
const moviePromise=new Promise((resolve,reject)=>{
setTimeout(()=>{
// resolve ({name: 'wrestling it Dad!', Rating: 9.2, year: 2019});
reject(Error('No moviePromise'))
},500);
});
// Promise.all([usersPromise,moviePromise])
Promise.race([usersPromise,moviePromise])
.then(responses=>{
// deconstruction assignment
const [users,movie]=responses;
console.log(users);
console.log(movie);
})
.catch(err=>{
console.error(err);
})