例子 :
function timeout(ms,num){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(num)
},ms)
})
}
async function asyncPrint(value, ms) {
var a = await timeout(ms,1);
console.log(a)
var b = await timeout(ms,2);
console.log(b)
console.log(value)
return value + 'world' // async 返回一个Promise对象,他的值是async函数中,return返回的值。
}
asyncPrint('hello',2000).then(res=>console.log(res))
// 1 2s后输出
// 2 4s后输出
// hello 4s后输出
// helle world 4s后输出
async function f() {
return 'hello world';
}
f().then(v => console.log(v))
// 函数声明
async function foo() {}
// 函数表达式
const foo = async function () {};
// 对象的方法
let obj = { async foo() {} };
obj.foo().then(...)
// Class 的方法
class Storage {
constructor() {
this.cachePromise = caches.open('avatars');
}
async getAvatar(name) {
const cache = await this.cachePromise;
return cache.match(`/avatars/${name}.jpg`);
}
}
const storage = new Storage();
storage.getAvatar('jake').then(…);
// 箭头函数
const foo = async () => {};
async function f() {
await Promise.reject('出错了');
// 或者
// return Promise.reject('出错了');
}
f()
.then(v => console.log(v))
.catch(e => console.log(e))
async function f() {
await Promise.reject('出错了');
await Promise.resolve('hello world'); // 不会执行
}
async function f() {
try {
await Promise.reject('出错了');
} catch(e) {
}
return await Promise.resolve('hello world');
}
// 或者
async function f() {
await Promise.reject('出错了')
.catch(e => console.log(e));
return await Promise.resolve('hello world');
}
f()
.then(v => console.log(v))
// hello world
async function Foo() {
throw new Error("error")
console.log('123')
}
Foo()
console.log("456")
// 456
// Uncaught (in promise) Error: error
async function f() {
await Promise.reject('出错了');
}
f().catch(e => console.log(e))
// 出错了
或者
async function f() {
await Promise.reject('出错了').catch(err=>console.log(err));
}
f()
// 出错了
async function f() {
try {
await Promise.reject('出错了');
} catch(e) {
console.log(e)
}
return await Promise.resolve('hello world');
}
f()
// 出错了
let foo = await getFoo();
let bar = await getBar();
// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);
// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
// 这两种写法,getFoo和getBar都是同时触发,这样就会缩短程序的执行时间。
function bar(callback) {
callback()
}
async function Foo() {
bar(function () {
await "a"
})
}
Foo()
// Uncaught SyntaxError: Unexpected string
function spawn(genF) { // genF是一个 Generator 函数, 通过promise.then()返回callback实现自执行
return new Promise(function(resolve, reject) {
const gen = genF();
function step(nextF) {
let next;
try {
next = nextF();
} catch(e) {
return reject(e);
}
if(next.done) {
return resolve(next.value);
}
Promise.resolve(next.value).then(function(v) {
step(function() { return gen.next(v); });
}, function(e) {
step(function() { return gen.throw(e); });
});
}
step(function() { return gen.next(undefined); });
});
}