promise.all/ promise.race 简单实现
程序员文章站
2022-06-09 19:18:04
...
Promise.all = arr => {
let aResult = []; //用于存放每次执行后返回结果
return new _Promise(function (resolve, reject) {
let i = 0;
next(); // 开始逐次执行数组中的函数(重要)
function next() {
arr[i].then(function (res) {
aResult.push(res); // 存储每次得到的结果
i++;
if (i == arr.length) { // 如果函数数组中的函数都执行完,便resolve
resolve(aResult);
} else {
next();
}
})
}
})
};
// promise.race
function race(entries) {
var Constructor = this; // this 是调用 race 的 Promise 构造器函数。
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
关于面试
上一篇: string类的一些常见面试题