开始学习AJAX。问题是:为什么通过异步函数解码 ours 时response,我们得到一个对象 { id: 101 } - 它甚至从哪里读取?在处理过程中,.then我们会从链接中获得完整的对象数组吗?我期待异步函数也从引用返回一个对象数组,但它返回一个我不知道它来自哪里的对象。
fetch它应该在两种情况下都一样吗?await它只是等待函数完成fetch,仅此而已,它不添加任何内容。并且它本身返回一个 promise,在这两种情况下都fetch存储了对象的相同结果 。Response
处理方式.then:
const POSTS_URL = 'https://jsonplaceholder.typicode.com/posts';
const result = fetch(POSTS_URL, {
method: 'GET',
})
result
.then(response => response.json())
.then(result => console.log(result));
通过异步函数:
const POSTS_URL = 'https://jsonplaceholder.typicode.com/posts';
const createNewPost = async () => {
try {
isLoading = true;
const response = await fetch(POSTS_URL, {
method: 'POST',
})
if (!response.ok) {
throw new Error('Ошибка запроса');
}
const result = await response.json();
console.log('result', result);
} catch (error) {
console.log(error);
} finally {
isLoading = false;
}
};
createNewPost();
在第一种情况下,您通过 GET 请求发布,在第二种情况下,您显然是在添加新发布,因为 POST。id: 101 分别是添加帖子的类型代码。如果您需要获取帖子列表,请将 POST 替换为 GET