async function foo() {}
const foo = async function() {}
let obj = {async foo() {}}
obj.foo().then(...)
class Storage {
constructor() {
this.cachePromise = cache.open('avatars')
}
async getAvatar(name) {
const cache = await this.cachePromise
return cache.match(`/avatar/${name}.jpg`)
}
}
const storage = new Storage()
storage.getAvatar('jack').then(...)
const foo = async () => {}
async 函数的语法规则总体上比较简单,难点是错误处理机制。
async function f() {
return 'hello Async 函数';
}
f().then(v => console.log(v))
// 控制台会打印:hello Async 函数
async function f() {
throw new Error('出错了');
}
f().then(
v => console.log('resolve', v),
e => console.log('reject', e)
)
// 控制台会打印:reject Error: 出错了
async function getTitle(url) {
let response = await fetch(url)
let html = await response.text()
return html.match(/<title>([\s\S]+)<\/title>/i)[1]
}
getTitle('https://tc39.github.io/ecma262/').then(console.log)
async function f() {
return await 123;
}
f().then(console.log)
class Sleep {
constructor(timeout) {
this.timeout = timeout;
}
then(resolve, reject) {
const startTime = Date.now();
setTimeout(
() => resolve(Date.now() - startTime),
this.timeout
);
}
}
(async () => {
const sleepTime = await new Sleep(1000);
console.log(sleepTime)
})();
async function f() {
await Promise.reject('出错了');
}
f()
.then(v => console.log(v))
.catch(e => console.log(e))
async function f() {
let result = await Promise.reject('先就出错了');
result = await Promise.resolve('这里不会执行了。。呜呜');
return result;
}
f().then(console.log).catch(console.log)
// 写法一
async function f() {
try {
await Promise.reject('出错了')
} catch (e) {}
return await Promise.resolve('Ok');
}
f().then(console.log)
// 写法二
async function f() {
await Promise.reject('出错了').catch(e => console.log(e))
return await Promise.resolve('Ok');
}
f().then(console.log)
async function f() {
await new Promise(function (resolve, reject) {
throw new Error('出错了');
})
}
f().then(
v => console.log(v),
e => console.log(e)
)
.catch(console.log)
async 函数就是将 Generator 函数和自动执行器,包装在一个函数里。
async function fn(args) {
// ...
}
// 等同于
function fn(args) {
return spawn(function* () {
// ...
});
}
🔥BuildAdmin是一个永久免费开源,无需授权即可商业使用,且使用了流行技术栈快速创建商业级后台管理系统。