readyState 值 | 状态名称 | 描述 |
---|---|---|
0 | UNSENT | 请求已创建,但尚未通过 open() 方法初始化。 |
1 | OPENED | 请求已通过 open() 方法初始化,但尚未通过 send() 方法发送。 |
2 | HEADERS_RECEIVED | send() 方法已调用,响应头和响应状态码已接收。 |
3 | LOADING | 响应体正在接收,但尚未完成。 |
4 | DONE | 响应已完成,数据已接收完毕,可以在客户端进行处理。 |
status 状态码 | 含义 |
---|---|
200 | OK - 请求成功 |
201 | Created - 请求已成功,并且服务器创建了新的资源 |
204 | No Content - 请求成功,但没有要返回的信息 |
400 | Bad Request - 客户端请求无效 |
401 | Unauthorized - 客户端需要身份验证 |
403 | Forbidden - 服务器拒绝请求 |
404 | Not Found - 服务器找不到请求的资源 |
500 | Internal Server Error - 服务器内部错误 |
502 | Bad Gateway - 服务器作为网关或代理时收到无效响应 |
503 | Service Unavailable - 服务器暂时不可用 |
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
在这里,我们使用 "GET" 请求从 data.json 获取数据,并设置为异步(true)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功,处理响应数据
} else if (xhr.readyState === 4 && xhr.status !== 200) {
// 请求失败,处理错误
}
};
其中,readyState 的值表示请求的不同阶段,4 表示请求已完成。status 是 HTTP 状态码,200 表示请求成功。
xhr.send();
const responseData = JSON.parse(xhr.responseText);
<body>
<script>
function ajaxRequest(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(null, JSON.parse(xhr.responseText));
}
};
xhr.send();
}
let results = [];
let completedRequests = 0;
function handleResponse(data, index) {
results[index] = data;
if (++completedRequests === 2) {
console.log(results);
}
}
ajaxRequest("data1.json", function (error, data) {
handleResponse(data, 0);
});
ajaxRequest("data2.json", function (error, data) {
handleResponse(data, 1);
});
</script>
</body>
<body>
<script>
function ajaxRequest(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(null, JSON.parse(xhr.responseText));
}
};
xhr.send();
}
ajaxRequest("data1.json", function (error, data1) {
ajaxRequest("data2.json", function (error, data2) {
console.log([data1, data2]);
});
});
</script>
</body>
|属性/方法 描述 constructor 返回创建实例的Promise构造函数。 then 返回一个新的Promise,并处理Promise的完成(resolved)状态。 catch 返回一个新的Promise,并处理Promise的拒绝(rejected)状态。 finally 返回一个新的Promise,在Promise完成或拒绝后执行一段代码。
const promise = new Promise((resolve, reject) => {
//resolve('value');
//reject('reason');
});
console.dir(promise);
属性/方法 | 描述 |
---|---|
then |
返回一个新的Promise,并处理Promise的完成(resolved)状态。 |
catch |
返回一个新的Promise,并处理Promise的拒绝(rejected)状态。 |
finally |
返回一个新的Promise,在Promise完成或拒绝后执行一段代码。 |
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve('成功');
} else {
reject('失败');
}
}, 1000);
});
promise.then(
(result) => {
console.log(result);
},
(reason) => {
console.error(reason);
}
);
const promise = new Promise((resolve, reject) => {
resolve('成功');
reject('失败')
});
promise.then();
const promise = new Promise((resolve, reject) => {
resolve('成功');
resolve('成功');
});
promise.then((value) => {
console.log(value);
});
const promise = new Promise((resolve, reject) => {
reject('失败');
reject('失败');
});
promise.then(undefined, (error) => {
console.log(error);
});
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
promise.then((value) => {
console.log(value);
});
console.log('用户代码执行完毕');
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
promise.then(function (value) {
console.log(this);
});
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
promise.then(function (value) {
console.log(1, value);
});
promise.then(function (value) {
console.log(2, value);
});
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
let promise2 = promise.then(function (value) {
console.log(value);
throw new Error('then error');
});
promise2.then(undefined, function (err) {
console.log(err);
});
const promise = new Promise((resolve, reject) => {
//resolve('成功');
reject('失败');
});
let promise2 = promise.then();
promise2.then(function (value) {
console.log(value);
}, function (err) {
console.log(err);
});
let promise2 = promise.then(function (value) {
return promise2;
});
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
let promise2 = promise.then(function (value) {
return new Promise((resolve, reject) => {
resolve('success');
//reject('fail');
});;
});
promise2.then(function (value) {
console.log(value);
}, function (reason) {
console.log(reason);
}
);
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
let promise2 = promise.then(function (value) {
let obj = {};
Object.defineProperty(obj, 'then', {
get() {
throw new Error();
}
});
return obj;
});
promise2.then(function (value) {
console.log(value);
}, function (reason) {
console.log(reason);
}
);
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
let promise2 = promise.then(function (value) {
let obj = {
then(resolvePromise, rejectPromise) {
//resolvePromise('成功2');
rejectPromise('失败2');
throw new Error('失败3');
}
};
return obj;
});
promise2.then(function (value) {
console.log(value);
},function (reason) {
console.log(reason);
});
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
let promise2 = promise.then(function (value) {
let obj = { name: 'zhufeng' };
Object.defineProperty(obj, 'then', {
get() {
return 'then string'
}
});
return obj;
});
promise2.then(function (value) {
console.log(value);
}, function (reason) {
console.log(reason);
}
);
const promise = new Promise((resolve, reject) => {
resolve('成功');
});
let promise2 = promise.then(function (value) {
return [1, 2, 3];
});
promise2.then(function (value) {
console.log(value);
}, function (reason) {
console.log(reason);
}
);
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject('出错了');
}, 1000);
});
promise.catch((reason) => {
console.error(reason);
});
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve('成功');
} else {
reject('失败');
}
}, 1000);
});
promise
.finally(() => {
console.log('无论如何都会执行');
});
function ajaxRequest(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error(xhr.statusText));
}
}
};
xhr.send();
});
}
ajaxRequest("data1.json")
.then(data1 => {
console.log(data1);
return ajaxRequest("data2.json");
})
.then(data2 => {
console.log(data2);
})
.catch(error => {
console.error("An error occurred:", error);
});
静态方法 | 描述 |
---|---|
Promise.all | 返回一个 Promise,该 Promise 在所有给定的 Promise 都已解决时解决,并且返回所有 Promise 的解决值数组,顺序与传入的 Promise 数组顺序一致。如果传入的任何 Promise 被拒绝,则返回的 Promise 将立即被拒绝,并且会传递拒绝的原因。 |
Promise.race | 返回一个 Promise,该 Promise 在给定的 Promise 数组中的任何一个 Promise 解决或拒绝时解决或拒绝。返回的 Promise 采用第一个解决或拒绝的 Promise 的值或原因。 |
Promise.resolve | 返回一个已解决的 Promise 对象,解析结果由传入的值决定。如果传入的是一个 Promise 对象,则返回该对象本身。如果传入的是一个 thenable 对象(即具有 then 方法的对象),则返回的 Promise 将采用该 thenable 对象的状态。否则,返回的 Promise 将以传入的值为解决值。 |
Promise.reject | 返回一个拒绝的 Promise 对象,拒绝原因由传入的值决定。 |
Promise.allSettled | 返回一个 Promise,该 Promise 在所有给定的 Promise 都已解决或拒绝后解决,并返回一个包含所有 Promise 结果的数组,每个结果是一个对象,包含该 Promise 的状态和值或原因。 |
Promise.any | 返回一个 Promise,该 Promise 在给定的 Promise 数组中的任何一个 Promise 解决时解决。如果所有 Promise 都被拒绝,则返回的 Promise 将被拒绝,并且会传递所有 Promise 的拒绝原因数组。 |
Promise.resolve(value);
Promise.resolve('Hello')
.then(value => {
console.log(value); // 'Hello'
return 42;
})
Promise.reject(reason);
Promise.reject(new Error('Something went wrong'))
.catch(error => {
console.error(error.message); // 'Something went wrong'
});
Promise.all(iterable);
const promise1 = Promise.resolve('Hello');
const promise2 = 42;
const promise3 = new Promise((resolve) => {
setTimeout(resolve, 1000, 'World');
});
Promise.all([promise1, promise2, promise3])
.then(values => {
console.log(values); // ['Hello', 42, 'World']
})
.catch(error => {
console.error(error);
});
通过 Promise.race 方法,可以同时启动多个异步操作,并使用最先解决或拒绝的 Promise 的结果进行后续处理
iterable:一个可迭代对象,包含多个 Promise 对象
Promise.race(iterable);
const promise1 = new Promise(resolve => setTimeout(resolve, 1000, 'Promise 1 resolved'));
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 500, 'Promise 2 rejected'));
const promise3 = new Promise(resolve => setTimeout(resolve, 1500, 'Promise 3 resolved'));
Promise.race([promise1, promise2, promise3])
.then(result => {
console.log(result); // 'Promise 2 rejected'
})
.catch(error => {
console.error(error); // 'Promise 2 rejected'
});
通过 Promise.any 方法,可以同时启动多个异步操作,并使用最快解决的 Promise 的结果进行后续处理
iterable:一个可迭代对象,包含多个 Promise 对象
Promise.any(iterable);
const promise1 = new Promise(resolve => setTimeout(resolve, 2000, 'Promise 1 resolved'));
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 1000, 'Promise 2 rejected'));
const promise3 = new Promise(resolve => setTimeout(resolve, 1500, 'Promise 3 resolved'));
Promise.any([promise1, promise2, promise3])
.then(result => {
console.log(result); // 'Promise 3 resolved'
})
.catch(errors => {
console.error(errors); // [AggregateError: All promises were rejected]
});
Promise.allSettled(iterable);
const promise1 = Promise.resolve('Resolved');
const promise2 = Promise.reject('Rejected');
const promise3 = new Promise(resolve => setTimeout(resolve, 1000, 'Delayed Resolved'));
Promise.allSettled([promise1, promise2, promise3])
.then(results => {
console.log(results);
/* [
{ status: 'fulfilled', value: 'Resolved' },
{ status: 'rejected', reason: 'Rejected' },
{ status: 'fulfilled', value: 'Delayed Resolved' }
] */
});
async function fetchUser() {
return "zhang";
}
const promise=fetchUser();
console.log(promise);
promise.then(value=>console.log(value))
async function fetchUser() {
const response = await fetch("data1.json");
const user = await response.json();
console.log(user);
}
fetchUser()
async function fetchUser() {
try {
const response = await fetch("data1.json");
const user = await response.json();
console.log(user);
} catch (error) {
console.error(error);
}
}