如何把async用到其他函数上
async function getAshColumns(id) {
const url = `xx/${ id }`
const res = await fetch(url)
return await res.json()
}
getAshColumns('test).then(res => {
console.log('res==>', res)
})
async function fun1() {}
const fun2 = async function () {}
const fun3 = async (id) => {}
如何在全局作用域下使用async
(async() => {
const data = await fun3()
})()
如何在类的函数上使用async
class Animal{
async fun5(){
const res = await fetch('')
return await res.json()
}
}
const animal = new Animal()
(async () => {
const data = await animal.fun5()
})()
如何处理async的错误
async function fun6() {
const res = fetch('')
if (res.status != 200) {
throw new Error(res.info)
}
}
const fun6Info = async () => {
try {
const data = fun6()
} catch (e) {
console.log('e==>', e);
}
}
如何处理代码中的串行与并行
const func = async () => {
const data1 = await getAshColumns(1)
const data2 = await getAshColumns(2)
const data1Promise = getAshColumns(1)
const data2Promise = getAshColumns(2)
const data3 = await data1Promise
const data4 = await data2Promise
}
如何让多个await执行并行
const func = async () => {
const [ data1, data2 ] = await Promise.all([
getAshColumns(1),
getAshColumns(2)
])
}
结合await和任意兼容.then()的代码
async function func() {
const number = await 666
console.log('number==>', number);
}
循环中使用await
const func = async () => {
const names = [ 'a', 'b' ]
for (const name of names) {
const data = await getAshColumns(name)
}
}
const func = async () => {
const names = [ 'a', 'b' ]
const promises = names.map(x => getAshColumns(x))
for (const name of promises) {
const data = await promises
}
}