async 和 await
特點(diǎn)
- 異步、非阻塞;
- 基于Promise實(shí)現(xiàn)的(強(qiáng)調(diào):不能用于普通的回調(diào)函數(shù));
- 簡(jiǎn)潔明了,異步編程新方式。
注意
await外層一定要有async包裹,不可單獨(dú)使用;
為何使用
- 代碼簡(jiǎn)潔,不再使用
.then()來(lái)包裹了,類(lèi)似寫(xiě)同步代碼,逐行編寫(xiě)代碼即可- 如果后臺(tái)返回的
httpcode非兩百的同時(shí)你又想處理里面的數(shù)據(jù),必須在.catch()中處理JSON.parse的錯(cuò)誤,但是如果使用try/catch加async/await處理起來(lái)就異常便捷
// 示例
const fetchData = async () => {
try {
const data = await getList();
console.log(data);
} catch (err) {
console.log(err);
}
};
如何代替
<script>
export default {
methods: {
// 可能以前你會(huì)這么調(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寫(xiě)法
checkDataIsSaved({cancelButtonText} = {cancelButtonText: "暫不保存"}) {
return new Promise(async (resolve, reject) => {
if (!equalsObj(this.oldTableData, this.tableData)) {
this.$confirm(
"檢測(cè)到未保存的內(nèi)容,是否在離開(kāi)頁(yè)面前保存修改?",
"確認(rèn)信息",
{
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)在寫(xiě)法
async checkDataIsSaved({cancelButtonText} = {cancelButtonText: "暫不保存"}) {
if (!equalsObj(this.oldTableData, this.tableData)) {
try {
await this.$confirm(
"檢測(cè)到未保存的內(nèi)容,是否在離開(kāi)頁(yè)面前保存修改?",
"確認(rèn)信息",
{
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(),無(wú)須擔(dān)心,在調(diào)用方法前全部加上await平鋪開(kāi)了寫(xiě)