本文主要是介绍Promise关键问题分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.如何修改对象的状态?
resolve函数 resolve(‘ok’);
reject函数 reject(‘error’);
throw ‘出问题了’
2.Promise可以指定多个回调
3.改变promise状态和指定回调函数谁先谁后?
都有可能,正常情况下先指定回调再改变状态(异步),但也可以先改状态再指定回调(同步状态)。
let p = new Promise((resolve,reject) => {resolve("OK");
});let result = p.then(value => { //result的结果为失败return new Promise((resolve,reject) => {rejected("error");});
4.串联多个任务
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
})
此处第二次console.log(value)输出结果为undefined, 因为then的返回结果是一个Promise,Promise的状态由它指定的函数状态的返回值来决定,这里指定的是前一个then,前一个then返回值没声明,所以输出undefined
5.Promise异常穿透现象
只需要再最后指定一个失败的回调,中间有任务失败,最后也会报出异常
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.如何终端Promsie链
返回一个状态为padding的promise
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);
})
这篇关于Promise关键问题分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!