promise实现ajax【每日一题】

503 阅读1分钟

比较简单,哈哈,每天积累一点

首先实现一个简单的的promise

 <script>
    var fun = new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(111);
        }, 1000)
        console.log('我创建了新的promise');
    })
    fun.then((x) => {
        console.log(x);
    })
</script>

promise实现ajax

 <script>
        var myAjax = (url) => {
            return new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest()
                xhr.open('get', url)
                xhr.send(data)
                xhr.onreadystatechange = () => {
                    if (xhr.status == 200 && readyState == 4) {
                        var json = JSON.parse(xhr.responseText)
                        resolve(json)
                    } else {
                        reject('error')
                    }
                }
            })
        }
    </script>
    
    
    

顺便问问有木有大佬可以内推呀!!