class 手写promse
时间: 2023-10-15 14:24:34 浏览: 107
class 手写Promise:
def __init__(self, executor):
self.status = 'pending'
self.value = None
self.on_resolve = []
self.on_reject = []
def resolve(value):
if self.status == 'pending':
self.status = 'resolved'
self.value = value
for callback in self.on_resolve:
callback(self.value)
def reject(reason):
if self.status == 'pending':
self.status = 'rejected'
self.value = reason
for callback in self.on_reject:
callback(self.value)
try:
executor(resolve, reject)
except Exception as e:
reject(e)
def then(self, on_fulfilled=None, on_rejected=None):
def _on_fulfilled(value):
if callable(on_fulfilled):
try:
result = on_fulfilled(value)
if isinstance(result, Promise):
result.then()
except Exception as e:
self.on_reject(e)
elif on_fulfilled is not None:
self.on_resolve.append(on_fulfilled)
def _on_rejected(reason):
if callable(on_rejected):
try:
result = on_rejected(reason)
if isinstance(result, Promise):
result.then()
except Exception as e:
self.on_reject(e)
elif on_rejected is not None:
self.on_reject.append(on_rejected)
if self.status == 'resolved':
_on_fulfilled(self.value)
elif self.status == 'rejected':
_on_rejected(self.value)
else:
self.on_resolve.append(_on_fulfilled)
self.on_reject.append(_on_rejected)
return self
def catch(self, on_rejected=None):
return self.then(None, on_rejected)
@staticmethod
def resolve(value):
return Promise(lambda resolve, reject: resolve(value))
@staticmethod
def reject(reason):
return Promise(lambda resolve, reject: reject(reason))
@staticmethod
def all(promises):
results = []
count = len(promises)
def _on_resolve(i, value):
results[i] = value
nonlocal count
count -= 1
if count == 0:
Promise.resolve(results)
def _on_reject(reason):
Promise.reject(reason)
for i, promise in enumerate(promises):
promise.then(lambda value, i=i: _on_resolve(i, value), _on_reject)
return Promise
@staticmethod
def race(promises):
def _on_resolve(value):
Promise.resolve(value)
def _on_reject(reason):
Promise.reject(reason)
for promise in promises:
promise.then(_on_resolve, _on_reject)
return Promise
阅读全文