三点运算符
用来取代arguments
function fun(...values) {
console.log(arguments);
// arguments.forEach(function (item, index) {
// console.log(item, index);
// });
console.log(values);
values.forEach(function (item, index) {
console.log(item, index);
})
}
fun(1,2,3);
let arr = [2,3,4,5,6];
let arr1 = ['abc',...arr, 'fg'];
console.log(arr1);
Promise对象:代表了未来某个将要发生的事件(通常是一个异步操作)
ES6的Promise是一个构造函数, 用来生成promise实例
promise对象的3个状态
- pending: 初始化状态
- fullfilled: 成功状态
- rejected: 失败状态
<script type="text/javascript">
// //创建一个promise实例对象
// let promise = new Promise((resolve, reject) => {
// //初始化promise的状态为pending---->初始化状态
// console.log('1111');//同步执行
// //启动异步任务
// setTimeout(function () {
// console.log('3333');
// //根据异步任务的返回结果去修改promise的状态
// //异步任务执行成功 这两个数都是函数
// resolve('hh') //修改promise状态为 fullfilled成功状态
// //异步任务执行失败
// // reject('hh')//修改promise的状态为rejected 失败的状态
// },2000)
// });
// console.log('222')
// //来调用实例对象中then成功或失败的回调
// promise
// .then((data) => {//标识成功的回调
// console.log(data , '成功了')
// } , (error) => {//失败的回调
// console.log('失败了')
// })
//定义获取新闻的功能函数
function getNews(url) {
let promise = new Promise((resolve ,reject) => {
//状态:初始化
//执行异步任务
//创建实例对象
let xmlHttp = new XMLHttpRequest()
//绑定监听 readystate
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState ===4 ){//请求成功
if (xmlHttp.status == 200) {
console.log(xmlHttp.responseText)
//修改状态,修改promise状态为成功状态
resolve(xmlHttp.responseText)
}else{//请求失败
reject('暂时没有新闻内容')
}
}
}
//open 设置请求的方式以及url
xmlHttp.open('GET' , url)
//发送
xmlHttp.send()
})
return promise
}
getNews('http://localhost:3000/news?id=2')
.then((data) => {
console.log(data)
//为发送请求获取评论内容url
let commentsUrl = JSON.parse(data).commentsUrl
let url = 'http://localhost:3000' + commentsUrl
//发送请求
return getNews(url)//返出去为了下面.then能找到
}, (error) => {
console.log(error)
})
.then((data) => {
console.log(data)
},() => {
})
</script>
这里先暂停,需要去看Ajax,这个地方压根就没学。