promise.ts
export function showAlert() {
console.log("开始调用showAlert");
return new Promise((reslove, reject) => {
try {
console.log("开始执行showAlert");
setTimeout(() => {
console.log("执行showAlert完成");
reslove();
}, 3000);
} catch (e) {
reject(e);
}
});
}
export function showAlert2() {
console.log("开始调用2");
return new Promise((reslove, reject) => {
try {
console.log("开始执行2");
setTimeout(() => {
console.log("执行2完成");
reslove();
}, 5000);
} catch (e) {
reject(e);
}
});
}
页面
import { showAlert, showAlert2 } from "../promise.ts";
- 打印数据
- 开始调用showAlert
- 开始执行showAlert
- 开始调用2
- 开始执行2
- 执行showAlert完成
- 已经结束
- 执行2完成
2结束
两个都调用
// 总共经过5秒 onSubmit() { showAlert() .then(res => { console.log("已经结束"); }) .catch(err => { console.log(err); }); showAlert2() .then(res => { console.log("2结束"); }) .catch(err => { console.log(err); }); }
异步调用
// 异步执行5秒完成 async onSubmit() { Promise.all([showAlert(), showAlert2()]).then(() => { console.log("两个执行完成"); }); }
async await
// 5秒完成 async onSubmit() { const result = await Promise.all([showAlert(), showAlert2()]); console.log("async await 执行完成"); }
await
// 8秒完成 async onSubmit() { await showAlert(); await showAlert2(); console.log("await完成"); }