什么是promise?
一个对象,用来处理异步操作。使异步操作写的更优雅、更易于阅读。
从字面上理解,promise是承诺、许诺的意思。意思是使用promise后,不管成功还是失败肯定会有返回值。
promise有三种状态:pending(进行中),resolved(完成),rejected(失败),只有异步返回的结构可以改变其状态。所以,promise的过程一般只有两种:pending->resolved或者pending到rejected。
promise对象还有一个比较常用的then方法,用来执
Promise.prototype.then(resolved,rejected)
var Pro = function (time) {
//返回一个Promise对象
return new Promise(function (resolve, reject) {
console.log('123');
//模拟接口调用
setTimeout(function () { //这里告诉Promise 成功了,然后去执行then方法 的第一个函数
resolve('成功返回');
}, time);
})
};
(function(){
console.log('start');
Pro(3000)
.then(function(data){
console.log(data);
return Pro(5000);})
.then(function(data){
console.log(data);
console.log('end');
})
})();
行回调函数,then方法接受两个参数
then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();});
promise.then(function() {
console.log('resolved.');
});
}
console.log('Hi!');
// Promise
// Hi!
// resolved
刚创建就会执行
原文地址:https://blog.csdn.net/weixin_62980497/article/details/137969356
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!