笔记-异步操作-回调、Promise与async、await

312 阅读1分钟

动态的往DOM中添加内容

通过回调实现

// 动态往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);
}

// getPosts();

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);
}

// getPosts();

function createPost(post) {
    // 实例化Promise对象
    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" });
    // createPost执行完之后才会执行getPosts()
    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); // ["hello world", 20, "goodbye"]
});

fetch的使用

async function fetchUsers() {
    // await或者then可以拿到结果
    const res =  await fetch("https://jsonplaceholder.typicode.com/users");
    const data = await res.json();
    console.log(data);
}
fetchUsers();