十分钟零基础了解Async

快速了解Async异步编程

1.基本语法

Async


async function testAsync() {
    return "hello async";
}

const result = testAsync();
console.log(result);

输出的是一个 Promise 对象。

c:\var\test> node --harmony_async_await .
Promise { 'hello async' }

await

await 可以理解为是 async wait 的简写。await 必须出现在 async 函数内部,不能单独使用。

    function notAsyncFunc() {
		await Math.random();
	}
	notAsyncFunc();//Uncaught SyntaxError: Unexpected identifier

await 后面可以跟任何的JS 表达式。虽然说 await 可以等很多类型的东西,但是它最主要的意图是用来等待 Promise 对象的状态被 resolved。如果await的是 promise对象会造成异步函数停止执行并且等待 promise 的解决,如果等的是正常的表达式则立即执行。

function sleep(second) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(' enough sleep~');
        }, second);
    })
}
function normalFunc() {
    console.log('normalFunc');
}
async function awaitDemo() {
    await normalFunc();
    console.log('something, ~~');
    let result = await sleep(2000);
    console.log(result);// 两秒之后会被打印出来
}
awaitDemo();
// normalFunc
// VM4036:13 something, ~~
// VM4036:15  enough sleep~

参考博文
https://segmentfault.com/a/1190000011526612

运用实例

通过async 和 await 一起使用可以节省大量代码

mounted() {
       axios.get('http://127.0.0.1:8000/home/index/index',{
           headers: {
               'Content-Type': 'application/x-www-form-urlencoded',
               'Accept': 'application/json'
           }
           }).then((res) => {
               if(res){
               console.log("ok")
               this.data = res.data
               console.log(res.data)
               }
           }).catch((error) => {
                   console.log(error)
           })
   },

这里使用axios发送请求,之前没有async的时候没什么,但是知道了async之后显得又长又臭…毫不夸张!!
使用async之后

 async getData(){
    let res = await Axios.get("http://127.0.0.1:8000/home/index/index")
    console.log(res)
  }

这就是async强大之处直接获取到res。好使博主也是才看到,今天初学还有很多东西不会,但是学到新东西的心情很激动,写个博客分享一下~
之后在学习其原理~加油!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值