本文数据来源:2022.stateofjs.com/zh-Hans/fea…
Promise.any
MDN连接
接收一个Promise数组,返回第一个状态变为resolve的Promise返回值
const pErr = new Promise((resolve, reject) => {
reject("Always fails");
});
const pSlow = new Promise((resolve, reject) => {
setTimeout(resolve, 500, "Done eventually");
});
const pFast = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "Done quick");
});
Promise.any([pErr, pSlow, pFast]).then((value) => {
console.log(value);
// pFast fulfills first
});
// Logs:
// Done quick
和Promise.all相比:Promise.all()会等所有Promise执行完后,返回所有Resolve的Promise值,并且只要其中一个值变为rejected,整个Promise.all状态变为rejected并返回。 和Promise.race相比:Promise.race()返回第一个发生变化的Promise值,不确定是resolve还是rejected
Promise.allSettled
promise.allSettled在所有的Promise的状态都改变后,才会返回最终状态(就算有失败,也会等待返回)
Promise.allSettled([
Promise.resolve(33),
new Promise((resolve) => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error("an error")),
]).then((values) => console.log(values));
// [
// { status: 'fulfilled', value: 33 },
// { status: 'fulfilled', value: 66 },
// { status: 'fulfilled', value: 99 },
// { status: 'rejected', reason: Error: an error }
// ]
Array.prototype.at
没啥好说的,返回指定index的值。但是可以通过index为负数,返回末尾的值,这个属性还是挺好用的,不需要用类似array[array.length - 1]的方法取值了
const array1 = [5, 12, 8, 130, 44];
let index = 2;
console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// Expected output: "Using an index of 2 the item returned is 8"
index = -2;
console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// Expected output: "Using an index of -2 item returned is 130"
top await
在
js module中可以在顶层使用await,不需要async包装
// html type设置为module模块
<html>
<script src="./entry.js" type="module"></script>
</html>
// entry.js
import {show} from "./subImport/e.js"
show();
// e.js
await new Promise(() => console.log("Promise"))
export const show = function() {
console.log("eShow");
}
成功执行await