17-1、Promise是什么

39 阅读1分钟
<script>
    // 1.认识Promise
    // Promise是异步操作的一种解决方案
    // document.addEventListener('click', () => {
    //     console.log('这里是异步的');
    // })
    // console.log('这里是同步的');

    // 2.什么时候使用Promise
    // Promise 一般来解决层层嵌套的回调函数(回调地狱 callback hell)的问题
    const move = (el, { x = 0, y = 0 } = {}, end = () => { }) => {
        el.style.transform = `translate3d(${x}px,${y}px,0)`;

        el.addEventListener(
            'transitionend',
            () => {
                // console.log('end');
                end();
            },
            false
        );
    };
    const boxEl = document.getElementById('box');

    document.addEventListener('click', () => {
        move(boxEl, { x: 150 }, () => {
            move(boxEl, { x: 150, y: 150 }, () => {
                move(boxEl, { y: 150 }, () => {
                    move(boxEl, { x: 0, y: 0 })
                })
            })
        })
    }, false)
</script>