JavaScript实现Promise流程详解
什么是Promise?
Promise是ES6中引入的一种异步编程解决方案,它将异步操作的结果包装成一个对象,从而让操作更加规范和便捷。Promise最大的特点就是解决了“回调地狱”问题。
Promise的基本用法
Promise对象有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。当异步操作执行成功时,状态由pending变为fulfilled,同时会将异步操作的结果传递给fulfilled回调函数;当异步操作执行失败时,状态由pending变为rejected,同时会将失败原因传递给rejected回调函数。
let promise = new Promise(function(resolve, reject) {
// resolve和reject是两个函数,表示异步操作的结果
if(/* 异步操作成功 */) {
resolve('success');
} else {
reject(new Error('failure'));
}
});
promise.then(function(value) {
console.log(value);
}, function(error) {
console.log(error);
});
Promise的链式调用
由于每次调用then方法都会返回一个新的Promise对象,因此Promise支持链式调用。可以通过链式调用,将多个异步操作串联在一起,使代码更加简洁明了。
let promise = new Promise(function(resolve, reject) {
resolve('success');
});
promise.then(function(value) {
console.log(value);
return new Promise(function(resolve, reject) {
resolve('more success');
});
}).then(function(value) {
console.log(value);
});
Promise的常见应用场景
Promise已广泛应用于JavaScript中的异步编程,常见的应用场景包括以下:
延时执行
function delay(ms) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, ms);
});
}
delay(1000).then(function() {
console.log('延时1秒后执行');
});
多个异步操作
Promise.all([
// 异步操作1
new Promise(function(resolve, reject) {
setTimeout(resolve, 1000, '1');
}),
// 异步操作2
new Promise(function(resolve, reject) {
setTimeout(resolve, 2000, '2');
})
]).then(function(result) {
console.log(result); // ['1', '2']
});
Promise实现代码
下面是一个简单的Promise实现代码,仅供参考。
function MyPromise(executor) {
let self = this;
self.status = 'pending'; // 状态
self.data = undefined; // Promise的结果
self.onResolvedCallback = []; // Promise resolved 时的回调函数集合
self.onRejectedCallback = []; // Promise rejected 时的回调函数集合
function resolve(value) {
if(self.status === 'pending') {
self.status = 'resolved';
self.data = value;
for(let i = 0; i < self.onResolvedCallback.length; i++) {
self.onResolvedCallback[i](value);
}
}
}
function reject(reason) {
if(self.status === 'pending') {
self.status = 'rejected';
self.data = reason;
for(let i = 0; i < self.onRejectedCallback.length; i++) {
self.onRejectedCallback[i](reason);
}
}
}
try{
executor(resolve, reject);
} catch(e) {
reject(e);
}
}
MyPromise.prototype.then = function(onResolved, onRejected) {
let self = this;
onResolved = typeof onResolved === 'function' ? onResolved : function(value) {return value;};
onRejected = typeof onRejected === 'function' ? onRejected : function(reason) {return reason;};
if(self.status === 'resolved') {
return new MyPromise(function(resolve, reject) {
try{
let x = onResolved(self.data);
if(x instanceof MyPromise) {
x.then(resolve, reject);
} else {
resolve(x);
}
} catch(e) {
reject(e);
}
});
}
if(self.status === 'rejected') {
return new MyPromise(function(resolve, reject) {
try{
let x = onRejected(self.data);
if(x instanceof MyPromise) {
x.then(resolve, reject);
} else {
resolve(x);
}
} catch(e) {
reject(e);
}
});
}
if(self.status === 'pending') {
return new MyPromise(function(resolve, reject) {
self.onResolvedCallback.push(function(value) {
try{
let x = onResolved(value);
if(x instanceof MyPromise) {
x.then(resolve, reject);
} else {
resolve(x);
}
} catch(e) {
reject(e);
}
});
self.onRejectedCallback.push(function(reason) {
try{
let x = onRejected(reason);
if(x instanceof MyPromise) {
x.then(resolve, reject);
} else {
resolve(x);
}
} catch(e) {
reject(e);
}
});
});
}
};
示例说明
下面是一个利用Promise实现延时执行的示例:
function delay(ms) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, ms);
});
}
delay(1000).then(function() {
console.log('延时1秒后执行');
});
上面的代码中,Promise对象包装了一个定时器,当定时器结束后,resolve回调函数被调用,Promise对象就从pending状态变为fulfilled状态,同时then方法中传入的回调函数也被执行,从而实现了延时执行的效果。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JavaScript实现Promise流程详解 - Python技术站