async 和 await 建立在 Promise 之上。 Promise 是 javascript 中的一个特殊对象,广泛用于避免 callback 地狱
在使用 async 和 await 时,try catch 块也很重要,因为我们还需要处理错误,以防 API 失败。
hasAccess: boolean;
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise < boolean > {
this.getCurrentUser();
return this.hasAccess;
}
async getCurrentUser() {
try {
const output1 = await Promise.resolve(fetch(urlOfToken).then(res => res.json())) // if GET call, if POST you can postData('', {})
const currentUser = await this.postData(
`URL fetching current user`,
{
token: `access token from object ${output} `,
param: 'any other param'
}
);
// Check in currentUser Object whether response contains user or not
// If user exists set this.hasAccess = true;
// IF not set this.hasAccess = false;
} catch (error) {
// Error Handling
console.log(error);
}
}
// Courtesy MDN
async postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
关于如何使用promises 以及async 和await 的额外参考。还介绍了如何进行并行、序列和竞赛 API 调用
const urls = [
'https://jsonplaceholder.typicode.com/users',
'https://jsonplaceholder.typicode.com/albums',
'https://jsonplaceholder.typicode.com/posts'
];
// BASIC
Promise
.all(urls.map(url => {
return fetch(url).then(res => res.json())
}))
.then((results) => {
console.log(results[0]);
console.log(results[1]);
console.log(results[2]);
})
.catch(() => console.log('error!'));
// async await
// built atop of promises
// benefit is it is easier to make code read easier nothing more promises can get job done actually
const getData = async function () {
try {
const [users, albums, posts] = await Promise.all(urls.map(url => {
return fetch(url).then(res => res.json())
}));
console.log('users', users);
console.log('albums', albums);
console.log('posts', posts);
} catch (error) {
console.log('Oops!');
}
}
// for await of
const getData2 = async function () {
const arrayOfPromises = await urls.map(url => fetch(url));
for await (let request of arrayOfPromises) {
const response = await request.json();
console.log(response);
}
}
const a = () => promisify('a', 100); // I am making it asynchronous here ; Can be API call or any asynchronus task
const b = () => promisify('b', 1000);// I am making it asynchronous here ; Can be API call or any asynchronus task
const c = () => promisify('c', 5000);// I am making it asynchronous here ; Can be API call or any asynchronus task
const promisify = (item, delay) =>
new Promise((resolve) =>
setTimeout(() =>
resolve(item), delay));
// Parallel
async function parallel() {
const [output1, output2, output3] = await Promise.all([a(), b(), c()]);
return `parallel done right: ${output1} , ${output2} , ${output3}`;
}
// race
async function race() {
const output1 = await Promise.race([a(), b(), c()]);
return `race done right: ${output1}`;
}
// sequence
async function sequence() {
const output1 = await a();
const output2 = await b();
const output3 = await c();
return `sequenece done right: ${output1}, ${output2}, ${output3}`;
}
parallel().then(console.log);
race().then(console.log);
sequence().then(console.log);