在浏览器里试了个例子
const p = new Promise(function(resolve,reject){
resolve('success');//这个必须有,否则会卡住,不执行then
console.log(1);
});
console.log(2);
p.then(function(value){
console.log(4);
});
console.log(3);
结果如下
Promise 对象只有:从 pending 变为 fulfilled 和从 pending 变为 rejected 的状态改变。只要处于 fulfilled 和 rejected ,状态就不会再变了即 resolved(已定型)
then 方法
then 方法接收两个函数作为参数,第一个参数是 Promise 执行成功时的回调,第二个参数是 Promise 执行失败时的回调,两个函数只会有一个被调用。
再来个例子,可以添加多个回调函数,它们会按照插入顺序并且独立运行。
const p = new Promise(function(resolve,reject){
console.log(0);
resolve(1);//这个resolve是成功之后执行的函数,代表着执行成功,并且把值传给then
}).then(function(value){ // 第一个then // 1
console.log(value);
console.log('--1--');
return value * 2;
}).then(function(value){ // 第二个then // 2
console.log(value);console.log('--2--');
}).then(function(value){ // 第三个then // undefined
console.log(value);//上一波then没有return 所以undefined
return Promise.resolve('resolve');
}).then(function(value){ // 第四个then // resolve
console.log(value);
return Promise.reject('reject');
}).then(function(value){ // 第五个then //reject:reject
console.log('resolve:' + value); //reject直接走error
}, function(err) {
console.log('reject:' + err);
});
结果如下
then 方法将返回一个 resolved 或 rejected 状态的 Promise 对象用于链式调用,且 Promise 对象的值就是这个返回值。