动态的往DOM中添加内容
通过回调实现
const posts = [
{ title: "post one", body: "this is post one" },
{ title: "post two", body: "this is post two" },
];
function getPosts() {
setTimeout(() => {
let output = "";
posts.forEach((post, index) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post,callback) {
setTimeout(() => {
posts.push(post);
callback();
},2000)
}
createPost({ title: "Post three", body: "this is post three" },getPosts);
通过Promise实现
const posts = [
{ title: "post one", body: "this is post one" },
{ title: "post two", body: "this is post two" },
];
function getPosts() {
setTimeout(() => {
let output = "";
posts.forEach((post, index) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if(!error) {
resolve();
}else{
reject("Error: something went run ");
}
}, 2000);
});
}
createPost({ title: "Post three", body: "this is post three" })
.then(getPosts)
.catch(err=>{
console.log(err);
});
通过async、await实现
async function init() {
await createPost({ title: "Post three", body: "this is post three" });
getPosts();
}
init();
Promise.all 和 fetch
Promise.all的使用
const promise1 = Promise.resolve("hello world");
const promise2 = Promise.resolve(20);
const promise3 = new Promise((resolve,reject)=>{
setTimeout(resolve("goodbye"),2000);
});
const promise4 = fetch("https://jsonplaceholder.typicode.com/users").then(res=>res.json());
Promise.all([promise1,promise2,promise3,promise4]).then((values)=>{
console.log(values);
});
fetch的使用
async function fetchUsers() {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await res.json();
console.log(data);
}
fetchUsers();