P粉6330757252023-08-19 13:31:19
Here, your addPost is not a promise function. That's why when you write "await addPost" it looks like it reinitializes the variable addPost. In order for this to work, you need to call the promise function. This way it will perform the promise work after you call it.
The following is your modified code
const posts = [{ title: 'Post 1' }, { title: 'Post 2' }]; var count = 3; const diffFunction = async () => { const addPost = () => new Promise((resolve, reject) => { setTimeout(() => { posts.push({ title: `Post ${count}` }); count++; resolve(count); }, 1000) }); const deletePost = () => new Promise((res, rej) => { setTimeout(() => { const deltedPost = posts.pop(); res(deltedPost); }, 2000) }); const showDetails = () => { posts.forEach(element => { console.log(element.title); }); } await addPost(); await addPost(); showDetails(); } diffFunction();
If this is clear to you, please let me know.
Thanks
P粉7703754502023-08-19 13:07:09
When you create a promise using new Promise()
, it starts running immediately. You can test this by running code like new Promise(() => { console.log("hello") })
in the console - you should see a log immediately.
You can achieve the behavior you want by defining a function that returns a new Promise. This way, your promise will only run when the function is called, and each function call will return a different Promise.
const posts = [{ title: 'Post 1' }, { title: 'Post 2' }]; var count = 3; const addPost = () => new Promise((resolve, reject) => { setTimeout(() => { posts.push({ title: `Post ${count}` }); count++; resolve(count); }, 1000) }) const deletePost = () => new Promise((res, rej) => { setTimeout(() => { const deltedPost = posts.pop(); res(deltedPost); }, 2000) }) const showDetails = () => { posts.forEach(element => { console.log(element.title); }); } const diffFunction = async () => { await addPost(); await addPost(); showDetails(); } diffFunction();