万字详解JavaScript手写一个Promise攻略
什么是Promise
Promise是一个JS的异步编程解决方案,对于那些需要等待其他代码执行完成(网络请求等)才可以执行的代码块提供了更好的控制方法。
Promise对象有三种状态: pending
, resolve
, reject
。pending状态表示等待执行,resolve状态表示完成执行,而reject状态表示执行失败。
手写Promise实现
下面我们来手写一个Promise实现,此Promise有then
与catch
方法对完成状态与失败状态进行处理。
pseudo code:
var Promise = function (executor) {
this.status = 'pending';
this.value = null;
this.reason = null;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
var resolve = function (value) {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach(function (callback) {
callback();
});
}
};
var reject = function (reason) {
if (this.status === 'pending') {
this.status = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(function (callback) {
callback();
});
}
};
try {
executor(resolve.bind(this), reject.bind(this));
} catch (err) {
reject.bind(this)(err);
}
};
Promise.prototype.then = function (onFulfilled, onRejected) {
if (this.status === 'pending') {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.onFulfilledCallbacks.push(function () {
try {
var result = onFulfilled(self.value);
resolve(result);
} catch (err) {
reject(err);
}
});
self.onRejectedCallbacks.push(function () {
try {
var reason = onRejected(self.reason);
resolve(reason);
} catch (err) {
reject(err);
}
});
});
}
if (this.status === 'fulfilled') {
var promise = new Promise(function (resolve, reject) {
try {
var result = onFulfilled(this.value);
resolve(result);
} catch (err) {
reject(err);
}
});
}
if (this.status === 'rejected') {
var promise = new Promise(function (resolve, reject) {
try {
var reason = onRejected(this.reason);
resolve(reason);
} catch (err) {
reject(err);
}
});
}
return promise;
};
Promise.prototype.catch = function (onRejected) {
return this.then(null, onRejected);
};
其中,我们定义了一个executor函数(这个函数会立马被执行),并需要通过该函数手写实现Promise对象的resolve,reject等方法和属性,以及then和catch方法。
Promise用例
下面来看一个使用手写Promise实现异步编程的例子,其中我们模拟了一个网络请求,若请求成功,则进行下一步处理并调用resolve方法,否则调用reject方法。
var request = new Promise(function(resolve, reject) {
setTimeout(function() {
var result = {
status: 200,
data: {
message: 'Request has been successfully processed.'
}
};
resolve(result);
}, 1000);
});
request.then(function(response) {
console.log(response.data.message);
return response;
})
.then(function(response) {
console.log('Request has been successfully handled.');
})
.catch(function(error) {
console.log(error);
});
在上面的例子中,我们可以看到我们用request变量来接收手写Promise对象的实例,并在then方法里对成功状态进行处理,并对catch方法进行错误状态的处理。
再来看另外一个类似的例子,这里我们会尝试Promise.all方法,它可以让我们同时执行多个Promise对象,而且只有所有的Promise get resolve状态,才会执行all对应的回调。
var request1 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Request 1 is finished.');
}, 1000);
});
var request2 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Request 2 is finished.');
}, 2000);
});
var request3 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Request 3 is finished.');
}, 3000);
});
Promise.all([request1, request2, request3])
.then(function (responses) {
responses.forEach(function (response) {
console.log(response);
});
console.log('All requests are finished.');
});
结语
以上是手写Promise实现的攻略以及部分应用场景,可能需要不断的添加对promise对象异步编程解决方案的理解和熟悉,来实现优质高效的代码逻辑。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:万字详解JavaScript手写一个Promise - Python技术站