ES2017-Async

38次阅读

共计 2684 个字符,预计需要花费 7 分钟才能阅读完成。

async 函数

 用于实现异步执行事件

返回值:一个 Promise 对象,这个 Promise 对象当 async 函数开始执行时被创建。当 async 函数返回值时,Promise 的 resolve 方法会传递这个值。当 async 函数抛出异常时,Promise 的 reject 方法会传递这个异常。示例 1:async 函数返回值
    假设 async 函数返回的 Promise 对象为 p
    a) 如果 return 一个 Promise, 意味着 p 现在反映了这个 Promise 的状态。async function asyncFunc() {return Promise.resolve(123);
        }
        asyncFunc()
        .then(x => console.log(x)); // 123
     
    b) 如果 return 一个非 Promise 的值,则用这个值实现 p
        async function asyncFunc() {return 123;}
        asyncFunc()
        .then(x => console.log(x)); // 123
    
示例 2:async 函数抛出异常
    async function asyncFunc() {throw new Error('Problem!');
    }
    asyncFunc()
    .catch(err => console.log(err));  // Error: Problem!

await 操作符

 用于等待一个 Promise 对象。a) 它只能在 async function 中使用。b) await 只影响直接包含它的异步函数
返回值:返回 Promise 对象的处理结果。a) 如果等待的不是 Promise 对象,则返回该值本身。示例 1:await 在非 async 函数中使用,会出现语法错误
     function asyncFunc() {
        let res = await 123;
        return res;
    }
    asyncFunc()
    // Uncaught SyntaxError: await is only valid in async function


    示例 2:await 等待非 promise
        async function asyncFunc() {
            let res = await 123;
            console.log(res); // 123
            return res;
        }
        asyncFunc()
            .then(x => console.log(x)); // 123

    示例 3:await 等待 promise 对象
        async function asyncFunc() {let res = await Promise.resolve(123);
            console.log(res);// Promise {<resolved>: 123 ...}
            return res;
        }
        asyncFunc()
            .then(x => console.log(x)); // 123

await 是按顺序执行的, Promise.all() 是并行执行的

a) 按顺序等待两个 Promise
    async function fun() {const result1 = await func1();
        const result2 = await func2();}
    
    func1
    |-----------|
                func2
                |--------------------|
                                     fun 执行完

b) 等待一个 Promise,这个 Promise 是一个包含两个元素的数组
    async function fun() {const [result1, result2] = await Promise.all([func1(),
            func2(),]);
    }

    func1
    |-----------|
        func2
        |--------------------|
                              fun 执行完

a) 适用于 func2 的执行必须在 func1 执行完后才有效的场景
b) 使用于 func2 和 func1 互相不影响的场景 

async 使用

 示例 1:获取 http://example.com 页面

async function fetchData(url) {
    try {let response = await fetch(url);
        let text = await response.text();
        return text;
    } catch (error) {throw new Error(error);
    }
}
fetchData("https://cors-anywhere.herokuapp.com/http://example.com")
    .then(data => console.log(data))
    .catch(err => console.log(err));

fetchData 的返回值为 promise p
执行流程图如下:

 示例 2:按顺序请求多个 url 结果
    async function fetchData(urls) {
        try {let results = [];
            for (const url of urls) {const response = await fetch(url);
                let text = await response.text();
                results.push(text);
            }
            return results;
        } catch (error) {throw new Error(error);
        }
    }
    const urls = [
        "https://cors-anywhere.herokuapp.com/http://example.com",
        "https://cors-anywhere.herokuapp.com/http://www.w3school.com.cn/"
        
    ];
    fetchData(urls)
        .then(data => console.log(data))
        .catch(err => console.log(err));

 示例 3:并行请求多个 url 结果
    async function fetchData(urls) {
        try {let promises = urls.map(async (url) => {const response = await fetch(url);
                return response.text();});
            let results = await Promise.all(promises);
            return results;
        } catch (error) {throw new Error(error);
        }
    }
    
    const urls = [
        "https://cors-anywhere.herokuapp.com/http://www.w3school.com.cn/",
        "https://cors-anywhere.herokuapp.com/http://example.com"
    ];
    fetchData(urls)
        .then(data => console.log(data))
        .catch(err => console.log(err));

正文完
 0