es6中Async函数有什么用-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

es6中Async函数有什么用

这篇文章将为大家详细讲解有关es6中Async函数有什么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

创新互联公司是一家专业的成都网站建设公司,我们专注网站建设、做网站、网络营销、企业网站建设,友情链接广告投放平台为企业客户提供一站式建站解决方案,能带给客户新的互联网理念。从网站结构的规划UI设计到用户体验提高,创新互联力求做到尽善尽美。

async 函数

async 函数,使得异步操作变得更加方便。它是 Generator 函数的语法糖。

Generator 函数,依次读取两个文件:

var fs = require('fs');
var readFile = function (fileName) {
 return new Promise(function (resolve, reject) {
 fs.readFile(fileName, function(error, data) {
  if (error) reject(error);
  resolve(data);
 });
 });
};
var gen = function* () {
 var f1 = yield readFile('/etc/fstab');
 var f2 = yield readFile('/etc/shells');
 console.log(f1.toString());
 console.log(f2.toString());
};

写成async函数,就是下面这样:

var asyncReadFile = async function () {
 var f1 = await readFile('/etc/fstab');
 var f2 = await readFile('/etc/shells');
 console.log(f1.toString());
 console.log(f2.toString());
};

async函数对 Generator 函数的改进,体现在以下四点:

1)内置执行器

Generator 函数的执行必须靠执行器,所以才有了co模块,而async函数自带执行器。也就是说,async函数的执行,与普通函数一模一样,只要一行。

var result = asyncReadFile();

上面的代码调用了asyncReadFile函数,然后它就会自动执行,输出最后结果。这完全不像 Generator 函数,需要调用next方法,或者用co模块,才能真正执行,得到最后结果。

2)更好的语义

async和await,比起星号和yield,语义更清楚了。async表示函数里有异步操作,await表示紧跟在后面的表达式需要等待结果。

3)更广的适用性

co模块约定,yield命令后面只能是 Thunk 函数或 Promise 对象,而async函数的await命令后面,可以是Promise 对象和原始类型的值(数值、字符串和布尔值,但这时等同于同步操作)。

4)返回值是 Promise

async函数的返回值是 Promise 对象,这比 Generator 函数的返回值是 Iterator 对象方便多了。你可以用then方法指定下一步的操作。

进一步说,async函数完全可以看作多个异步操作,包装成的一个 Promise 对象,而await命令就是内部then命令的语法糖。

一、基本用法

async函数返回一个 Promise 对象,可以使用then方法添加回调函数。当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。

function timeout(ms) {
 return new Promise((resolve) => {
 setTimeout(resolve, ms);
 });
}
async function asyncPrint(value, ms) {
 await timeout(ms);
 console.log(value);
}
asyncPrint('hello world', 5000);

上面代码指定5000毫秒以后,输出hello world。

由于async函数返回的是 Promise 对象,可以作为await命令的参数。所以,上面的例子也可以写成下面的形式:

async function timeout(ms) {
 await new Promise((resolve) => {
 setTimeout(resolve, ms);
 });
}
async function asyncPrint(value, ms) {
 await timeout(ms);
 console.log(value);
}
asyncPrint('hello world', 5000);

async 函数多种使用形式

// 函数声明
async function foo() {}
// 函数表达式
const foo = async function () {};
// 对象的方法
let obj = { async foo() {} };
obj.foo().then(...)
// 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('hzzly').then(…);
// 箭头函数
const foo = async () => {};

二、语法

async函数的语法规则总体上比较简单,难点是错误处理机制。

返回 Promise 对象

async函数返回一个 Promise 对象。async函数内部return语句返回的值,会成为then方法回调函数的参数。

async function f() {
 return 'hello world';
}
f().then(v => console.log(v))
// "hello world"

Promise 对象的状态变化

async函数返回的 Promise 对象,必须等到内部所有await命令后面的 Promise 对象执行完,才会发生状态改变,除非遇到return语句或者抛出错误。也就是说,只有async函数内部的异步操作执行完,才会执行then方法指定的回调函数。

async function getTitle(url) {
 let response = await fetch(url);
 let html = await response.text();
 return html.match(/([\s\S]+)<\/title>/i)[1];
}
getTitle('https://tc39.github.io/ecma262/').then(console.log)
// "ECMAScript 2017 Language Specification"</pre><p>上面代码中,函数getTitle内部有三个操作:抓取网页、取出文本、匹配页面标题。只有这三个操作全部完成,才会执行then方法里面的console.log。</p><p><strong>三、使用注意点</strong></p><p>await命令后面的Promise对象,运行结果可能是rejected,所以最好把await命令放在try…catch代码块中。</p><pre>async function myFunction() {
 try {
 await somethingThatReturnsAPromise();
 } catch (err) {
 console.log(err);
 }
}
// 另一种写法
async function myFunction() {
 await somethingThatReturnsAPromise()
 .catch(function (err) {
 console.log(err);
 };
}</pre><p>多个await命令后面的异步操作,如果不存在继发关系,最好让它们同时触发。</p><pre>//异步操作(即互不依赖),被写成继发关系。这样比较耗时,因为只有getFoo完成以后,才会执行getBar,完全可以让它们同时触发。
let foo = await getFoo();
let bar = await getBar();
// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);
// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;</pre><p>await命令只能用在async函数之中,如果用在普通函数,就会报错。</p><p>关于“es6中Async函数有什么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。</p>            
            
                        <br>
            网页题目:es6中Async函数有什么用            <br>
            浏览地址:<a href="http://kswsj.cn/article/gggjeo.html">http://kswsj.cn/article/gggjeo.html</a>
        </div>
    </div>
    <div class="other">
        <h3>其他资讯</h3>
        <ul>
            <li>
                    <a href="/article/ppecsc.html">利用java怎么将二维数组转换为json</a>
                </li><li>
                    <a href="/article/ppecec.html">Mysql中常用函数有什么</a>
                </li><li>
                    <a href="/article/ppecsd.html">c++异常3</a>
                </li><li>
                    <a href="/article/ppecsp.html">计算机网络中怎么快速查看和删除系统共享的目录和磁盘</a>
                </li><li>
                    <a href="/article/ppecic.html">java如何实现学生信息管理系统</a>
                </li>        </ul>
    </div>
</div>
<div class="line"></div>
<!--底部-->
<footer id="5">
    <div class="foot1 container">
        <div class="list">
            <div class="item">
                <a href="javascript:;">
                    <span class="ico1"><i class="iconfont"></i><img src="/Public/Home/img/ewm.png" alt=""></span>
                    <strong>关注我们</strong>
                </a>
            </div>
            <div class="item">
                <a href="" target="_blank">
                    <span><i class="iconfont"></i></span>
                    <strong>索要报价</strong>
                </a>
            </div>
            <div class="item">
                <a href="" target="_blank">
                    <span><i class="iconfont"></i></span>
                    <strong>我要咨询</strong>
                </a>
            </div>
            <div class="item">
                <a href="" target="_blank">
                    <span><i class="iconfont"></i></span>
                    <strong>找到我们</strong>
                </a>
            </div>
            <div class="item">
                <a href="" target="_blank">
                    <span><i class="iconfont"></i></span>
                    <strong>投诉建议</strong>
                </a>
            </div>
        </div>
        <div class="tel">
            <dl>
                <tel><a href="tel:400-028-6601" target="_blank">400-028-6601</a></tel><br>
                <span>也许您需要专业的服务,欢迎来电咨询</span>
            </dl>
            <dl>
                <tel><a href="tel:18980820575" target="_blank">18980820575</a></tel><br>
                <span>您的需求,是我们前进的动力</span>
            </dl>
        </div>
    </div>
    <div class="friend">
        <div class="container">
            <span class="tit">友情链接:</span>
            <div class="inner">
                <a href="https://www.cdcxhl.com/" target="_blank">网站设计</a><a href="https://www.cdcxhl.com/xiangyingshi.html" target="_blank">响应式网站建设</a><a href="https://www.cdcxhl.com/zuyong/" target="_blank">成都服务器租用</a><a href="https://www.cdcxhl.com/hangyead/" target="_blank">广告投放</a><a href="https://www.cdcxhl.com/" target="_blank">成都做网站</a><a href="https://www.cdcxhl.com/xiyun.html" target="_blank">西云服务器托管</a><a href="https://www.cdcxhl.com/douyin/" target="_blank">抖音代运营</a><a href="https://www.cdcxhl.com/xiangyingshi.html" target="_blank">成都响应式网站建设公司</a><a href="https://www.cdcxhl.com/ruanwen/" target="_blank">发布软文</a><a href="https://www.cdcxhl.com/tuoguan/yaan/" target="_blank">雅安云锦天府</a><a href="https://www.cdcxhl.com/sosuo.html" target="_blank">网站排名优化</a><a href="https://www.cdcxhl.com/xiyun.html" target="_blank">移动主机托管</a><a href="https://www.cdcxhl.com/gaofang/" target="_blank">成都高防服务器租用</a><a href="https://www.cdcxhl.com/douyin/" target="_blank">抖音视频拍摄</a><a href="https://www.cdcxhl.com/tuoguan/" target="_blank">成都服务器托管</a><a href="https://www.cdcxhl.com/cloud/" target="_blank">成都云服务器租用</a><a href="https://www.cdcxhl.com/" target="_blank">网站建设公司</a><a href="https://www.cdcxhl.com/ruanwen/" target="_blank">软文推广营销</a>            </div>
        </div>
    </div>
    <div class="foot">
        <div class="container">
            <div class="footNav">
                <h3>网站建设</h3>
                <a href="http://www.cqcxhl.com/" target="_blank">网站建设公司</a><a href="https://www.cdcxhl.com/waimao.html" target="_blank">外贸营销网站建设</a><a href="http://www.cxjianzhan.com/" target="_blank">网站建设公司</a>            </div>
            <div class="footNav">
                <h3>服务器托管</h3>
                <a href="http://www.cdfuwuqi.com/tuoguan/duoxian/" target="_blank">多线服务器托管</a><a href="https://www.cdcxhl.com/idc/ziyang.html" target="_blank">资阳天府云计算中心</a><a href="http://www.cdxwcx.cn/tuoguan/mianyang.html" target="_blank">绵阳服务器托管</a>            </div>
            <div class="footNav">
                <h3>网站制作</h3>
                <a href="https://www.cdxwcx.com/" target="_blank">网站制作</a><a href="http://seo.cdkjz.cn/wangzhan/" target="_blank">网站制作公司</a><a href="http://chengdu.cdxwcx.cn/" target="_blank">成都网站制作</a>            </div>
            <div class="footNav">
                <h3>企业服务</h3>
                <a href="https://www.cdcxhl.com/service/gongsizhuce.html" target="_blank">注册公司</a><a href="https://www.cdcxhl.com/link/" target="_blank">友情链接购买</a><a href="https://www.cdcxhl.com/ruanwen/yingxiao/" target="_blank">软文发布平台</a>            </div>
            <div class="fr ecode">
                <div class="fl">
                    <img src="/Public/Home/img/ewm.jpg">
                    <p>关注企业微信</p>
                </div>
                <div class="fr slogan">
                    <p class="icon">
                        <a class="ph" href=""><i class="iconfont"></i></a>
                        <a class="qq" href="tencent://message/?uin=1683211881&Site=&Menu=yes"><i class="iconfont"></i></a>
                    </p>
                    <p>
                        <i>想要找 </i> <a href="">小程序开发</a>、<a href="">APP开发</a>、
                        <a href="">营销型网站建设</a>、<a href="">网站建设</a>、
                        <i><a href="">网站定制开发</a></i> ,就选<a href="">创新互联</a>
                    </p>
                </div>
            </div>
        </div>
        <div class="bottom container">
            <p class="fl">
                版权所有:成都创新互联科技有限公司
                备案号:<a href="https://beian.miit.gov.cn/" target="_blank" rel="nofollow">蜀ICP备19037934号</a>
                服务热线:028-86922220
            </p>
            <p class="fr">
                <a href="https://www.cdxwcx.com/" target="_blank">成都网站建设</a>:
                <a href="https://www.cdcxhl.com/" target="_blank">创新互联</a>
            </p>
        </div>
    </div>
</footer>
<!--在线咨询-->
<div class="fot">
    <ul>
        <li>
            <a href="https://p.qiao.baidu.com/cps/mobileChat?siteId=11284691&userId=6256368&type=1&reqParam=%20{%22from%22:0,%22sessionid%22:%22%22,%22siteId%22:%2211284691%22,%22tid%22:%22-1%22,%22userId%22:%226256368%22,%22ttype%22:1,%22siteConfig%22:%20{%22eid%22:%226256368%22,%22queuing%22:%22%22,%22siteToken%22:%226ce441ff9e2d6bedbdfc2a4138de449e%22,%22userId%22:%226256368%22,%22isGray%22:%22false%22,%22wsUrl%22:%22wss://p.qiao.baidu.com/cps3/websocket%22,%22likeVersion%22:%22generic%22,%22siteId%22:%2211284691%22,%22online%22:%22true%22,%22webRoot%22:%22//p.qiao.baidu.com/cps3/%22,%22bid%22:%22160142915792139572%22,%22isSmallFlow%22:0,%22isPreonline%22:0,%22invited%22:0%20},%22config%22:%20{%22themeColor%22:%224d74fa%22%20}%20}&appId=&referer=&iswechat=0&expectWaiter=-1&openid=null&otherParam=null&telephone=null&speedLogId=null&eid=null&siteToken=6ce441ff9e2d6bedbdfc2a4138de449e" target="_blank">
                <img src="/Public/Home/img/fot1.png" alt="">
                <p>在线咨询</p>
            </a>
        </li>
        <li>
            <a href="tel:18980820575" target="_blank">
                <img src="/Public/Home/img/fot2.png" alt="">
                <p>拨打电话</p>
            </a>
        </li>
    </ul>
</div>
</body>
</html>
<script>
    $(".con img").each(function(){
        var src = $(this).attr("src");    //获取图片地址
        var str=new RegExp("http");
        var result=str.test(src);
        if(result==false){
            var url = "https://www.cdcxhl.com"+src;    //绝对路径
            $(this).attr("src",url);
        }
    });
    window.onload=function(){
        document.oncontextmenu=function(){
            return false;
        }
    }
</script>