标签:event type eve set resolve ons value lse 问题:
arr.slice(0)
arr.concat()
let obj2 = {... obj}
function deepClone(obj){
//判断参数是不是一个对象
let objClone = new obj.constructor();
if(obj && typeof obj==="object"){
for(key in obj){
if(obj.hasOwnProperty(key)){
//判断ojb子元素是否为对象,如果是,递归复制
if(obj[key]&&typeof obj[key] ==="object"){
objClone[key] = deepClone(obj[key]);
}else{
//如果不是,简单复制
objClone[key] = obj[key];
}
}
}
}
return objClone;
}
回调地狱:上一个回调函数中继续做事情,而且继续回调(在真实项目的AJAX请求中经常出现回调地狱)=>异步请求、不方便代码的维护
Promise的诞生就是为了解决异步请求中的回调地狱问题:它是一种设计模式,ES6中提供了一个JS内置类Promise,来实现这种设计模式
function ajax1() {
return new Promise(resolve => {
$.ajax({
url: ‘/student‘,
method: ‘get‘,
data: {
class: 1
},
success: resolve
});
});
}
function ajax2(arr) {
return new Promise(resolve => {
$.ajax({
url: ‘/score‘,
method: ‘get‘,
data: {
stuId: arr
},
success: resolve
});
});
}
function ajax3() {
return new Promise(resolve => {
$.ajax({
url: ‘/jige‘,
// ...
success: resolve
});
});
}
ajax1().then(result => {
return ajax2(result.map(item => item.id));
}).then(result => {
return ajax3();
}).then(result => {
});
new Promise的时候先执行executor函数,在这里开启了一个异步操作的任务(此时不等:把其放入到EventQuque任务队列中),继续执行
let p1 = new Promise((resolve, reject) => {
setTimeout(_ => {
let ran = Math.random();
console.log(ran);
if (ran < 0.5) {
reject(‘NO!‘);
return;
}
resolve(‘OK!‘);
}, 1000);
});
p1.then(result => {
console.log(`成功:` + result);
}, reason => {
console.log(`失败:` + reason);
});
let p1 = new Promise((resolve, reject) => {
resolve(100);
});
let p2 = p1.then(result => {
console.log(‘成功:‘ + result);
return result + 100;
}, reason => {
console.log(‘失败:‘ + reason);
return reason - 100;
});
let p3 = p2.then(result => {
console.log(‘成功:‘ + result);
}, reason => {
console.log(‘失败:‘ + reason);
});
TEHN中也可以只写一个或者不写函数
遇到一个THEN,要执行成功或者失败的方法,如果此方法并没有在当前THEN中被定义,则顺延到下一个对应的函数
AWAIT会等待当前PROMISE的返回结果,只有返回的状态是RESOLVED情况,才会把返回结果赋值给RESULT
AWAIT不是同步编程,是异步编程(微任务):当代码执行到此行(先把此行),构建一个异步的微任务(等待PROMISE返回结果,并且AWAIT下面的代码也都被列到任务队列中),
async function fn() {
console.log(1);
let result = await p2;
console.log(result);
let AA = await p1;
console.log(AA);
}
fn();
console.log(2); */
async function fn() {
let reason = await p3;
console.log(reason);
}
fn(); */
标签:event type eve set resolve ons value lse 问题:
原文地址:https://www.cnblogs.com/smilestudio/p/13030378.html