1、Promise.withResolvers()
Promise.withResolvers() 允许创建一个新的 Promise,并同时获得 resolve 和 reject 函数。
// 以前实现方法
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
// Promise.withResolvers()实现方法
const { promise, resolve, reject } = Promise.withResolvers();
// 在这里可以使用 resolve 和 reject 函数
setTimeout(() => resolve('成功!'), 1000);
promise.then(value => {
console.log(value); // 输出: 成功!
});
2、Object.groupBy()
Object.groupBy()方法用于数组分组。
// 传统实现对象分组
const fruits = [
{ name: "Apple", color: "red" },
{ name: "Banana", color: "yellow" },
{ name: "Cherry", color: "red" },
{ name: "Lemon", color: "yellow" },
{ name: "Grape", color: "purple" },
];
const fruitsByColor = {};
fruits.forEach(fruit => {
const color = fruit.color;
if (!fruitsByColor[color]) {
fruitsByColor[color] = [];
}
fruitsByColor[color].push(fruit);
});
console.log(fruitsByColor);
// Object.groupBy()实现对象分组
const fruitsByColor = Object.groupBy(fruits, (fruit) => fruit.color)