- function ajax(url, method, data) {
- return new Promise((resolve, reject) => {
- const xhr = new XMLHttpRequest();
- xhr.open(method, url);
- xhr.setRequestHeader('Content-Type', 'application/json');
- xhr.onreadystatechange = function () {
- if (this.readyState === 4) {
- if (this.status >= 200 && this.status < 300) {
- resolve(JSON.parse(this.responseText));
- } else {
- reject({
- status: this.status,
- statusText: xhr.statusText
- });
- }
- }
- };
- xhr.onerror = function () {
- reject({
- status: this.status,
- statusText: xhr.statusText
- });
- };
- xhr.send(JSON.stringify(data));
- });
- }
调用方法:
- ajax('/api/test', 'POST', {foo: 'bar'})
- .then(data => console.log(data))
- .catch(error => console.error(error));
以上代码的含义是:发送一个 POST 请求到 URL /api/test
,数据为 {foo: 'bar'}
,返回一个 Promise 对象,使用 then 方法处理成功的回调函数,使用 catch 方法处理失败的回调函数。
Promise是JavaScript中一种非常常用的异步编程解决方案。它可以非常方便地处理异步操作,避免了回调函数的嵌套过多而导致代码难以维护的问题。
Promise的主要作用是将异步操作封装成一个对象,通过then方法向外界提供成功和失败的回调函数,使得异步操作的结果可以通过回调函数进行处理。简单来说,Promise的作用就是让异步操作变得像同步操作一样,更加易于理解和编写。
- function getData(url) {
- return new Promise(function(resolve, reject) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url);
- xhr.onreadystatechange = function() {
- if(xhr.readyState === 4) {
- if(xhr.status >= 200 && xhr.status < 300) {
- resolve(xhr.responseText);
- } else {
- reject(new Error(xhr.statusText));
- }
- }
- };
- xhr.onerror = function() {
- reject(new Error('Network Error'));
- };
- xhr.send();
- });
- }
-
- // 使用方式
- getData('https://example.com/api/data')
- .then(function(data) {
- console.log(data);
- })
- .catch(function(error) {
- console.log(error);
- });
在这个例子中,我们封装了一个名为getData的函数,该函数接收一个URL参数,返回一个Promise对象。我们使用XMLHttpRequest对象发送一个GET请求,当请求完成时,根据请求的状态码来决定resolve还是reject Promise。如果请求成功,我们将返回响应文本;如果请求失败,则返回一个Error对象。
使用时,我们可以通过then方法来注册成功的回调函数,catch方法来注册失败的回调函数。这样,无论getData函数返回的Promise对象是成功还是失败,我们都可以方便地处理它的结果。