async function myAsyncFunc(){
try {
const fulfilledValue = await promise
}catch(rejectValue){
console.error('error:', rejectValue)
}
}
复制代码
函数定义以前使用了
async
关键字,就能够在函数内使用await
。 当您await
某个Promise
时,函数暂停执行,直至该Promise
产生结果,而且暂停并不会阻塞主线程。 若是Promise
执行,则会返回值。 若是Promise
拒绝,则会抛出拒绝的值。javascript
function logFetch(url) {
return fetch(url)
.then(response => response.text())
.then(text => {
console.log(text);
}).catch(err => {
console.error('fetch failed', err);
});
}
复制代码
async function logFetch(url) {
try {
const response = await fetch(url);
// 打印成功获取的数据
console.log(await response.text());
}
catch (err) {
// 一样的抛出错误
console.log('fetch failed', err);
}
}
复制代码
去掉了万恶的 return 回调函数,是否是代码清爽不少了。java
await
,异步函数都会返回 Promise
。该 Promise
解析时返回异步函数返回的任何值,拒绝时返回异步函数抛出的任何值。所以,对于:web
// wait ms milliseconds
function wait(ms) {
return new Promise(r => setTimeout(r, ms));
}
async function hello() {
await wait(500);
return 'world';
}
复制代码
…调用 hello() 返回的 Promise 会在执行时返回 "world"。promise
async function foo() {
await wait(500);
throw Error('bar');
}
复制代码
…调用 foo() 返回的 Promise 会在拒绝时返回 Error('bar')。异步
function logInOrder(urls) {
// 先使用咱们上面写好的 fetch 函数获取全部的数据
const textPromises = urls.map(url => {
return fetch(url).then(response => response.text());
});
// 而后用 reduce 把前面的 promises 一一的进行处理
textPromises.reduce((chain, textPromise) => {
return chain.then(() => textPromise)
.then(text => console.log(text));
}, Promise.resolve());
}
复制代码
async function logInOrder(urls) {
for (const url of urls) {
const response = await fetch(url);
console.log(await response.text());
}
}
复制代码
这样是否是简洁不少,可是这样的话咱们的第二次获取数据要在第一次数据获取完毕才能开始,这样就牺牲了性能,可是咱们还有更好的方法async
async function logInOrder(urls) {
// 使用 map,和 async 改写,这样能够并行获取数据
const textPromises = urls.map(async url => {
const response = await fetch(url);
return response.text();
});
for (const textPromise of textPromises) {
console.log(await textPromise);
}
}
复制代码
上面的代码解决了咱们并行获取数据的时间问题,又能按照我么你的需求一一按顺序打印咱们的数据函数
const mySync = async url=> {
try {
const response = await fetch(url);
console.log(await response.text());
}
catch (err) {
console.log('fetch failed', err);
}
}
复制代码
const storage = {
async getAvatar(name) {
const cache = await caches.open('avatars');
return cache;
}
};
storage.getAvatar('jaffathecake').then(…);
复制代码
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('jaffathecake').then(…);
复制代码