zoukankan      html  css  js  c++  java
  • ECMAScript2017之async function

    An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

    Remember, the await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.

    function getHtml(url) {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.onload = () => {
                resolve(xhr.responseText);
            };
            xhr.onerror = () => {
                reject(xhr.statusText)
            };
            xhr.send();
        }).then(
            val=>{
                return getTitle(val);
            }
        );
    }
    function getTitle(html){
        return html.substring(html.indexOf('<title>')+7,html.indexOf('</title>'));
    }
    async function printTitle(){
        console.log(new Date().getTime());
        //  暂停执行,直到Promise被resolve或reject后,继续执行
        var title = await getHtml('https://www.baidu.com');
        console.log(new Date().getTime(),title);
    }
    printTitle();

  • 相关阅读:
    二分查找
    二分排序
    How to use hdu?
    HGOI 20200721
    HGOI 20200720
    HGOI 20190719
    HGOI 20200716
    HGOI 20190714
    LCA 的一些扩展算法
    HGOI 20190711
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/8995463.html
Copyright © 2011-2022 走看看