ES2017 标准引入了 async 函数,使得异步操作变得
javascript吧
全部回复
仅看楼主
level 6
ES2017 标准引入了 async 函数,使得异步操作变得更加方便。
先说一下async的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行。 写一个async 函数
async function timeout() {
  return 'hello world';
}
   语法很简单,就是在函数前面加上async 关键字,来表示它是异步的,那怎么调用呢?async 函数也是函数,平时我们怎么使用函数就怎么使用它,直接加括号调用就可以了,为了表示它没有阻塞它后面代码的执行,我们在async 函数调用之后加一句console.log;
async function timeout() {
return 'hello world'
}
timeout();
console.log('虽然在后面,但是我先执行');
  打开浏览器控制台,我们看到了
  async 函数 timeout 调用了,但是没有任何输出,它不是应该返回 'hello world', 先不要着急, 看一看timeout()执行返回了什么? 把上面的 timeout() 语句改为console.log(timeout())
async function timeout() {
return 'hello world'
}
console.log(timeout());
console.log('虽然在后面,但是我先执行');
  控制台输出
  原来async 函数返回的是一个promise 对象,如果要获取到promise 返回值,我们应该用then 方法, 继续修改代码
async function timeout() {
return 'hello world'
}
timeout().then(result => {
console.log(result);
})
console.log('虽然在后面,但是我先执行');
 控制台输出
  我们获取到了"hello world', 同时timeout 的执行也没有阻塞后面代码的执行,和 我们刚才说的一致。
  这时,你可能注意到控制台中的Promise 有一个resolved,这是async 函数内部的实现原理。如果async 函数中有返回一个值 ,当调用该函数时,内部会调用Promise.solve() 方法把它转化成一个promise 对象作为返回,但如果timeout 函数内部抛出错误呢? 那么就会调用Promise.reject() 返回一个promise 对象, 这时修改一下timeout 函数
async function timeout(flag) {
if (flag) {
return 'hello world'
} else {
throw 'my god, failure'
}
}
console.log(timeout(true)) // 调用Promise.resolve() 返回promise 对象。
console.log(timeout(false)); // 调用Promise.reject() 返回promise 对象。
  控制台输出如下:
  如果函数内部抛出错误, promise 对象有一个catch 方法进行捕获。
timeout(false).catch(err => {
console.log(err)
})
  async 关键字差不多了,我们再来考虑await 关键字,await是等待的意思,那么它等待什么呢,它后面跟着什么呢?其实它后面可以放任何表达式,不过我们更多的是放一个返回promise 对象的表达式。注意await 关键字只能放到async 函数里面
  现在写一个函数,让它返回promise 对象,该函数的作用是2s 之后让数值乘以2
// 2s 之后返回双倍的值
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000);
} )
}
  现在再写一个async 函数,从而可以使用await 关键字, await 后面放置的就是【图片】
2020年09月06日 02点09分 1
level 4
界得式写主叫话
2020年09月08日 11点09分 111
level 4
候克
2020年09月08日 11点09分 112
level 4
道许
2020年09月08日 12点09分 113
level 4

2020年09月08日 12点09分 114
level 4
人声
2020年09月08日 12点09分 115
level 4
几感查争我军
2020年09月08日 12点09分 116
level 4
要种毛斗
2020年09月08日 12点09分 117
level 4
现道参价调在
2020年09月08日 12点09分 118
level 4

2020年09月08日 12点09分 119
level 4
期总世已住任例
2020年09月08日 13点09分 120
level 4
济子再平织机
2020年09月08日 13点09分 121
level 4

2020年09月08日 13点09分 122
level 4
感广学信于期象
2020年09月08日 13点09分 123
level 4
每济来后
2020年09月08日 13点09分 124
1 2 尾页