js基础之项目中promise和 async的用法
promise主要代码
Fun() {
new Promise(resolve => {
后端接口().then(() => {
resolve(0)
})
}).then(data => {
}
})
}
async主要代码
getRegionList().then(res => {
this.createdFun()
})
async createdFun() {
let configArea = await this.getPortraitFun()
},
getPortraitFun() {
return new Promise(resolve => {
后端接口({
参数:参数,
}).then(res => {
resolve(res.data || {})
})
})
},
async asyncFun() {
this.getOffice()
await this.fetchmemberInfoFindById();
},
async函数中,可以使用await表达式,async函数执行,遇到await,会先暂停,等到await后的异步执行完毕,再继续往后执行
function testAwait() {
return new Promise((resolve) => {
setTimeout(function () {
console.log("异步中的输出");
resolve();
}, 1000);
});
}
async function helloAsync() {
await testAwait();
console.log("async中的输出");
}
helloAsync();
function testAwait() {
return new Promise((resolve) => {
setTimeout(function () {
console.log("异步中的输出");
resolve();
}, 1000);
});
}
async function helloAsync() {
testAwait();
console.log("async中的输出");
}
helloAsync();
ajax中的async
async function fetchData() {
const response = await $.ajax({
url: 'example.com/api/data',
dataType: 'json'
});
console.log(response);
}
fetchData();
链接: https://pythonjishu.com/fmedzcpsteaocyz/