const posts = [{
title: 'Post One',
body: 'This is Post 1'
},
{
title: 'Post Two',
body: 'This is Post 2'
},
{
title: 'Post Three',
body: 'This is Post 3'
}
]
Я создаю массив сообщений здесь
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
Сначала я получаю сообщение с помощью get Post. Чтобы сделать это как запрос API, я делаю с setTimeoutFunction ();
function CreatePost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if (!error) {
resolve();
} else {
reject('Error Something Went wrong')
}
}, 2000)
})
}
Я создаю четвертый пост с CreatePost
function CreateAnotherPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if (!error) {
resolve(console.log(posts));
} else {
reject('something went wrong')
}
}, 5000);
})
}
Здесь я создаю еще один пост с очень долгим временем ожидания
CreateAnotherPost({
title: 'Post Five',
body: 'This is post Five'
}).then(CreatePost({
title: 'Post Four',
body: 'This is post Four'
})).then(getPosts).catch(error => console.log(error));
Я могу заставить его работать плавно с цепочкой .then. Но я не знаю, как использовать обещание. Все