使用promise封装ajax

 1 // Promise 封装 ajax
 2 function fetch(method, url, data){
 3     return new Promise((resolve, reject) => {
 4         var xhr = new XMLHttpRequest();
 5         var method = method || "GET";
 6         var data = data || null;
 7         xhr.open(method, url, true);
 8         xhr.onreadystatechange = function() {
 9             if(xhr.status === 200 && xhr.readyState === 4){
10                 resolve(xhr.responseText);
11             } else {
12                 reject(xhr.responseText);
13             }
14         }
15         xhr.send(data);
16         })
17 }
18 
19 // 使用
20 fetch("GET", "/some/url.json", null)
21 .then(result => {
22     console.log(result);
23 })
24 
25 // 封装 nodejs error first 风格回调
26 function readFile(url) {
27     return new Promise((resolve, reject) => {
28        fs.readFile(url,'utf8', (err, data) => {
29         if(err) {
30             reject(err);
31             return;
32         }
33         resolve(data)
34         }) 
35     })
36 }
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_24147051/article/details/87911065
posted @ 2020-12-20 12:21  NightWalker  阅读(29)  评论(0)    收藏  举报