ES6---async, await, promise 综合例子

ES6---async, await, promise 综合例子

  • new Promise(主线程代码).then(成功微任务, 失败微任务);
  • sync---替代promise
  • await---替代then

1.

<div id="aa"></div>
    <script type="text/javascript">
        // new Promise(主线程代码).then(成功微任务, 失败微任务);
        // async---替代promise
        // await---替代then

        var kk = [{ age: 18 }, { age: 19 }, { age: 20 }];
        console.log(kk);
        for (var i = 0; i < kk.length; i++) {
            document.getElementById("aa").innerHTML += '<div>' + kk[i].age + '</div>';
            console.log(kk[i]);
        }
    </script>

console:

2.

var kk = [{ age: 18 }, { age: 19 }, { age: 20 }];
        console.log(kk);

        //遍历循环
        for (const k_item of kk) {
            document.getElementById("aa").innerHTML += '<div>' + k_item.age + '</div>';
            console.log(k_item.age);

console:

3. 延迟效果

//延迟效果 setTimeout可以实现定时效果,但是,怎么知道它结束呢?
        //resolve, reject发通知,用then捕获
        var kk = [{ age: 18 }, { age: 19 }, { age: 20 }, { age: 22 }, { age: 40 }, { age: 25 }, { age: 23 }];
        console.log(kk);

        async function sleep(sec = 1000) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve();
                }, sec);
            });
        }
        async function show() {
            for (const k_item of kk) {
                //类似于Thread.sleep(500);
                await sleep(500); //卡住,卡到sleep()里面的promise发出了resolve()
                document.getElementById("aa").innerHTML += '<div>' + k_item.age + '</div>';
            };
        };
        show();

console:

页面间隔500ms显示

4.

//class 写死的写法
        class MyTask {
            then(resolve, reject) {
                console.log('123');

            };
        }

console:

5.

class MyTask {
            then(resolve, reject) {
                console.log('123');
                resolve('来自class的promise发出通知的值');
            };
        }

        var p = new MyTask();
        console.log(p);

        new Promise((resolve, reject) => {
            resolve('a123');
        }).then(result => {
            console.log(result);
            //不继续执行就不用return,否则需要return, 7种类型都可以
            return p;
        }, error => { }).then(
            result => {
                console.log(result);
            });

console:

6. 上面的代码用async await实现

class MyTask {
            then(resolve, reject) {
                console.log('123');
                resolve('来自class的promise发出通知的值');
            };
        }

        var p = new MyTask();

        async function ttt() {
            let result = await 'a123';
            console.log(result);
            let result2 = await p;
            console.log(result2);
        }
        ttt();

console:

(0)

相关推荐