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')
};