1 //定义一个请求news的方法 2 function getNews(url) { 3 //创建一个promise对象 4 let promise = new Promise((resolve, reject) => { 5 //初始化promise状态为pending 6 //启动异步任务 7 let request = new XMLHttpRequest(); 8 request.onreadystatechange = function () { 9 if(request.readyState === 4){ 10 if(request.status === 200){ 11 let news = request.response; 12 resolve(news); 13 }else{ 14 reject('请求失败了。。。'); 15 } 16 } 17 }; 18 request.responseType = 'json';//设置返回的数据类型 19 request.open("GET", url);//规定请求的方法,创建链接 20 request.send();//发送 21 }) 22 return promise; 23 } 24 25 getNews('http://localhost:3000/news?id=2') 26 .then((news) => { 27 console.log(news); 28 document.write(JSON.stringify(news)); 29 console.log('http://localhost:3000' + news.commentsUrl); 30 return getNews('http://localhost:3000' + news.commentsUrl); 31 }, (error) => { 32 alert(error); 33 }) 34 .then((comments) => { 35 console.log(comments); 36 document.write('<br><br><br><br><br>' + JSON.stringify(comments)); 37 }, (error) => { 38 alert(error); 39 })
ES6 promise的一个实例
猜你喜欢
转载自www.cnblogs.com/potato-lee/p/10302942.html
今日推荐
周排行