Promise.all()
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 300);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 200);
});
Promise.all([promise1, promise2]).then((res) => {
console.log(res[0]);
console.log(res[1]);
});
避免嵌套的 Promise 和 .then()
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('*');
}, 1000);
});
const twoStars = (star) => {
return (star + star);
};
const oneDot = (star) => {
return (star + '.');
};
const print = (val) => {
console.log(val);
};
// 将它们链接在一起
promise.then(twoStars).then(oneDot).then(print);
异步
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
// 异步函数表达式
const msg = async function() {
const msg = await helloWorld();
console.log('Message:', msg);
}
// 异步箭头函数
const msg1 = async () => {
const msg = await helloWorld();
console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- 2 秒后
msg1(); // Message: Hello World! <-- 2 秒后