promise 的中文叫做承诺
主要作用是:用于异步程序串行。
单个程序的执行方式:
同步:阻塞,必须等前面一个程序执行完毕以后,再去执行当前的程序。
异步:非阻塞,前面程序是否执行完毕,和当前程序没有任何关系。
描述多个程序之间的执行状态:
并行:A,B...可以同时执行或者不同时执行。
串行:执行A结束以后,再去执行B。
同步串行
异步并行
异步串行(promise保证异步程序串行)
console.log("启动定时器之前");
setTimeout(function(){
console.log("4秒到了");
}, 4000);
console.log("启动定时器之后");
console.log("启动定时器之前");
setTimeout(function(){
console.log("3秒到了");
}, 3000);
console.log("启动定时器之后");
console.log("启动定时器之前");
setTimeout(function(){
console.log("5秒到了");
}, 5000);
console.log("启动定时器之后");
console.time("test1");
setTimeout(function(){
console.log("4秒到了");
setTimeout(function(){
console.log("3秒到了");
setTimeout(function(){
console.log("5秒到了");
console.timeEnd("test1");
}, 5000)
}, 3000);
}, 4000);
Promise语法 构造函数
【注】Promise对象,后续只能跟一个.then方法
resolve 如果成功,调用的函数
.then(函数) 函数 == resolve
.catch(函数) 函数 == reject
reject 如果失败,调用函数
new Promise().then().catch();
new Promise().then(() => return new Promise()).then(...).catch()
var state = 0; //1 成功 0 失败
new Promise(function(resolve, reject
if(state){
resolve("成功");
}else{
reject("失败");
}
//异步程序1
}).then(function(msg){
console.log("then:" + msg);
//异步程序2
return new Promise()
}).then(function(函数){
}).catch(function(msg){
console.log("catch:" + msg);
})
//时间片转轮