async 与 await

async 关键字 
	1.含义:表示函数是一个异步函数,意味着该函数的执行不会阻塞后面代码的执行
	
	2.定义与调用
		async function hello (flag) {
		  if (flag) {
			return 'hello world'
		  } else {
			return 'my god,failure'
		  }
		}
		// async 函数返回的是一个promise 对象,如果要获取到promise 返回值,我们应该用then 方法
		console.log(hello(true))  //Promise {<resolved>: "hello world"}
		console.log(hello(false)) //Promise {<resolved>: "my god,failure"}
		hello(true).then(res => {
		  console.log(res)
		}).catch(err => {
		  console.log(err)
		})
		console.log('虽然在后面,但是我先执行');
		
	3.注意点:	
		1.async 函数 返回值是Promise 对象
		2.如果async函数内部有 await,必须等到此async函数内部的异步操作(await)执行完,才会执行then方法指定的回调函数

		
await 关键字
	1.含义:表示等待的意思,遇到await代码就不在向下执行,直到执行完毕才继续
	
	2.定义与调用

		function handleAfter2seconds (num) {
		  return new Promise((resolve, reject) => {
			setTimeout(() => {
			  resolve(2 * num)
			}, 2000);
		  })
		}

		async function result () {
		  let first = await handleAfter2seconds(30);
		  let second = await handleAfter2seconds(50);
		  let third = await handleAfter2seconds(30);
		  // 不需要等first执行完再去嵌套second执行再去嵌套third执行
		  //写异步代码就像写同步代码一样了,再也没有回调地域了
		  console.log(first + second + third) //220
		}

		result();

		
	注意:
		1.await 关键字只能放到async 函数里面
		2.await命令后面是一个 Promise 对象,返回该对象的结果。如果不是 Promise 对象,就直接返回对应的值。
			async function f() {
			  // 等同于
			  // return 123;
			  return await 123;
			}

			f().then(v => console.log(v)) //123
		
		3.await命令后面的Promise对象,运行结果可能是rejected,所以最好把await命令放在try...catch代码块中
			
			任何一个await语句后面的 Promise 对象变为reject状态,那么整个async函数都会中断执行。
				async function f() {
				  await Promise.reject('出错了');
				  await Promise.resolve('hello world'); // 不会执行
				}
			当希望即使前一个异步操作失败,也不要中断后面的异步操作。
				async function f() {
				  try {
					await Promise.reject('出错了');
				  } catch(err) {
					console.log(err);
				  }
				  return await Promise.resolve('hello world');
				}

				f().then(v => console.log(v))
				
				或者
					async function f() {
					  await somethingThatReturnsAPromise()
					  .catch(function (err) {
						console.log(err);
					  });
					}
		
		4.多个await命令后面的异步操作,如果不存在继发关系,最好让它们同时触发。
			例子:假设getFoo和getBar是两个异步的操作
					let foo = await getFoo();
					let bar = await getBar();
				按上面的写法比较耗时,可按下面改进:
					//getFoo和getBar都是同时触发,这样就会缩短程序的执行时间
					let [foo, bar] = await Promise.all([getFoo(), getBar()]);	

拓展:
	async 函数多种使用形式
	
		// 函数声明
		async function foo() {}

		// 函数表达式
		const foo = async function () {};

		// 箭头函数
		const foo = async () => {};

		// 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(…);


		// 对象的方法
		let obj = { async foo() {} };
		obj.foo().then(...)

  

猜你喜欢

转载自www.cnblogs.com/changxue/p/10810357.html