-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
3. 实现Promise.allSettled #3
Comments
Promise.myAllSettled = function (proms) {
return new Promise((resolve, reject) => {
let settledCount = 0; //状态已经确定的promise数
let count = 0; //promise总数
const result = [];
for (const prom of proms) {
let i = count;
count++;
Promise.resolve(prom).then(
(data) => {
settledCount++;
result[i] = {
status: "fullfilled",
value: data,
};
},
(reason) => {
settledCount++;
result[i] = {
status: "rejected",
reason,
};
}
).finally(() => {
if(settledCount >= count){
resolve(result)
}
});
}
});
};
const pro = new Promise((resolve, reject) => {
setTimeout(() => {
reject(3);
}, 1000);
});
Promise.allSettled([pro, Promise.resolve(1), Promise.reject(2)]).then(
(data) => {
console.log(data);
}
);
Promise.myAllSettled([pro, Promise.resolve(1), Promise.reject(2)]).then(
(data) => {
console.log(data);
}
); |
Promise.prototype.mySettled = function (promises) {
return new Promise((resolve) => {
const data = [],
len = promises.length;
let cnt = 0;
for (let i = 0; i < len; i++) {
const promise = promises[i];
Promise.resolve(promise)
.then(
(res) => {
data[i] = { status: "fulfilled", value: res };
},
(error) => {
data[i] = { status: "rejected", reason: error };
}
)
.finally(() => {
if (cnt === len) resolve(data);
});
}
});
};
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) =>
setTimeout(reject, 100, "foo")
);
const promises = [promise2, promise1];
Promise.allSettled(promises).then((results) =>
results.forEach((result) => console.log(result))
); |
function allSettled(promises) {
return Promise.all(promises.map(p => Promise.resolve(p).then(
value => ({ status: 'fulfilled', value }),
reason => ({ status: 'rejected', reason })
)));
} |
Promise.allSettled = function (ites) { |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: