async
和 await
特點
- 異步韩肝、非阻塞晤锥;
- 基于Promise實現(xiàn)的(強調(diào):不能用于普通的回調(diào)函數(shù))媳握;
- 簡潔明了,異步編程新方式嚣镜。
注意
await
外層一定要有async
包裹狈邑,不可單獨使用碗啄;
為何使用
- 代碼簡潔扒吁,不再使用
.then()
來包裹了,類似寫同步代碼隶垮,逐行編寫代碼即可- 如果后臺返回的
httpcode
非兩百的同時你又想處理里面的數(shù)據(jù)藻雪,必須在.catch()
中處理JSON.parse
的錯誤,但是如果使用try/catch
加async/await
處理起來就異常便捷
// 示例
const fetchData = async () => {
try {
const data = await getList();
console.log(data);
} catch (err) {
console.log(err);
}
};
如何代替
<script>
export default {
methods: {
// 可能以前你會這么調(diào)用
fetchData () {
getUserInfo().then((data) => {
const data = data
if (data.id) {
getList(data.id).then((res) => {
if (res.length > 0) {
getOtherList().then((response) => {
this.list = response.list
})
}
})
}
})
},
// 現(xiàn)在可以這么調(diào)用
async fetchData () {
const { id } = await getUserInfo();
if (id) {
const res = await getList();
if (res.length > 0) {
const { list } = await getOtherList();
this.list = list
}
}
}
}
}
</script>
配合 try/catch
用法
// promise寫法
checkDataIsSaved({cancelButtonText} = {cancelButtonText: "暫不保存"}) {
return new Promise(async (resolve, reject) => {
if (!equalsObj(this.oldTableData, this.tableData)) {
this.$confirm(
"檢測到未保存的內(nèi)容狸吞,是否在離開頁面前保存修改勉耀?",
"確認信息",
{
distinguishCancelAndClose: true,
confirmButtonText: "保存",
cancelButtonText: cancelButtonText,
type: "warning",
},
)
.then(() => {
this.ClickFn()
resolve();
})
.catch((action) => {
if (action === "cancel") {
resolve();
}
if (action === "close") {
throw new Error("取消成功指煎!");
}
});
} else {
resolve();
}
});
}
// 現(xiàn)在寫法
async checkDataIsSaved({cancelButtonText} = {cancelButtonText: "暫不保存"}) {
if (!equalsObj(this.oldTableData, this.tableData)) {
try {
await this.$confirm(
"檢測到未保存的內(nèi)容,是否在離開頁面前保存修改便斥?",
"確認信息",
{
distinguishCancelAndClose: true,
confirmButtonText: "保存",
cancelButtonText: cancelButtonText,
type: "warning",
},
);
}
catch (err) {
if (err === "close") {
throw new Error("取消成功至壤!");
}
}
if (data === "confirm") {
await this.ClickFn();
}
}
}
其他的替代使用
- 如果代碼中有使用到
.finally()
方法,try/catch
同樣也有try { } catch { } finally { }
2.如果需要使用
Promise.all()
枢纠,無須擔(dān)心像街,在調(diào)用方法前全部加上await
平鋪開了寫