ES6新特性——9.async

1.语法

语法:
async function name([param[, param[, ... param]]]) { statements }

name: 函数名称。

param: 要传递给函数的参数的名称。

statements: 函数体语句。

async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。

async function helloAsync(){
    return "helloAsync";
  }
  
console.log(helloAsync())  // Promise {<resolved>: "helloAsync"}
 
helloAsync().then(v=>{
   console.log(v);         // helloAsync
})

async 函数中可能会有 await 表达式,async 函数执行时,如果遇到await 就会先暂停执行 ,等到触发的异步操作完成后,恢复 async 函数的执行并返回解析值。

await 关键字仅在 async function 中有效。如果在 async function函数体外使用await ,会报错

function testAwait(){
   return new Promise((resolve) => {
       setTimeout(function(){
          console.log("testAwait");
          resolve();
       }, 1000);
   });
}
 
async function helloAsync(){
   await testAwait();
   console.log("helloAsync");
 }
helloAsync();
// testAwait
// helloAsync

2.await

await操作符用于等待一个 Promise 对象, 它只能在异步函数async function内部使用。

[return_value] = await expression;

expression: 一个 Promise 对象或者任何要等待的值。
  • Promise 对象:await会暂停执行,等待 Promise对象resolve,然后恢复 async函数的执行并返回解析值。
  • Promise对象:直接返回对应的值。

返回值
返回Promise对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。

如果一个Promise被传递给一个await操作符,await将等待Promise正常处理完成并返回其处理结果。

function testAwait (x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}
 
async function helloAsync() {
  var x = await testAwait ("hello world");
  console.log(x); 
}
helloAsync ();
// hello world

正常情况下,await命令后面是一个 Promise 对象,它也可以跟其他值,如字符串,布尔值,数值以及普通函数。

function testAwait(){
   console.log("testAwait");
}
async function helloAsync(){
   await testAwait();
   console.log("helloAsync");
}
helloAsync();
// testAwait
// helloAsync

3.并行

const fetch = require('node-fetch');

//定义睡眠函数,每次请求前都睡几秒
const sleep = (timeout=2000)=>new Promise(resolve => {
	setTimeout(resolve, timeout)
});

async function getZhihu(id){
	await sleep(2000);
	const url = ''
	const response = await fetch(url);
	return await response.json()
}

const showInfo = async () => {
	console.time('showTime')
	//这两个请求现在是并行的
	const req1 = getZhihu('fr');
	const req2 = getZhihu('tt');
	const resp1 = await req1;
	const resp2 = await req2;
	//console.log(`NAME:${}`)
	//如果写成下面这样就是串行
	`const resp1 = await getZhihu('fr')
	 const resp2 = await getZhihu('tt')
	`
}

showInfo();

可以先直接调用他的操作,然后await他的结果

或者用Promise.all实现并行方法
const [resp1, resp2] = await Promise.all([
	getZhihu('fr');
	getZhihu('tt');
]);

4.在循环中使用await


const fetch = require('node-fetch');
const bluebird = require('bluebird')
//定义睡眠函数,每次请求前都睡几秒


async function getZhihu(id){
	await sleep(2000);
	const url = ''
	const response = await fetch(url);
	return await response.json()
}
下面是串行
const showInfo = async ()=> {
	console.time('show colunmn');
	const names = ['fr', 'tt'];
	for (const name of names){
		const col = await getZhihu(name);
		console.log(col.name)	
	}
	console.timeEnd('show colunmn')
};
showInfo();

下面是并行
const showInfo = async ()=> {
	console.time('show colunmn');
	const names = ['fr', 'tt'];
	const promises = names.map(x => getZhihu(x));
	for (const promise of promises){
		const col = await promise;
		console.log(col.name)	
	}
	console.timeEnd('show colunmn')
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值