1. How to modify the status of an object?
resolve function resolve('ok');
reject function reject('error');
throw'something went wrong'
2. Promise can specify multiple callbacks
. 3. Change the state of the promise and specify the callback function.
It is possible to specify the callback first and then change the state (asynchronous) under normal circumstances, but you can also change the state first and then specify the callback (synchronous state).
let p = new Promise((resolve,reject) => {
resolve("OK");
});
let result = p.then(value => {
//result的结果为失败
return new Promise((resolve,reject) => {
rejected("error");
});
4. Concatenate multiple tasks
let p = new Promise((resolve,reject) => {
setTimeout(() => {
resolve("OK");
},1000);
});
p.then(value => {
return new Promise((resolve,reject) => {
resolve("success");
});
}).then(value => {
console.log(value); //success
}).then(value => {
console.log(value); //undefined
})
The output result of console.log(value) for the second time here is undefined, because the return result of then is a Promise, and the state of the Promise is determined by the return value of the function state specified by it. The specified here is the previous then, the previous The return value of then is not declared, so undefined is output
5. Promise abnormal penetration phenomenon
only needs to specify a failed callback at the end, if there is a task failure in the middle, an exception will be reported at the end
let p = new Promise((resolve,reject) => {
setTimeout(() => {
resolve("OK");
},1000);
});
p.then(value => {
return new Promise((resolve,reject) => {
resolve("success");
});
}).then(value => {
console.log('111'); //success
}).then(value => {
console.log('222'); //undefined
}).then(value => {
console.log('333'); //undefined
}).catch(reason => {
console.warn(reason);
})
6. How to terminate the Promsie chain and
return a promise with padding status
let p = new Promise((resolve,reject) => {
setTimeout(() => {
resolve("OK");
},1000);
});
p.then(value => {
return new Promise((resolve,reject) => {
resolve("success");
});
}).then(value => {
console.log('111');
return new Promise(() => {
});
}).then(value => {
console.log('222');
}).then(value => {
console.log('333');
}).catch(reason => {
console.warn(reason);
})