1

Мне нужно вывести сообщения на страницу, которые отправляются с моей страницы и со страницы моих подписчиков. У меня есть массив на сервере с данными полученный с помощью get запроса

0: {_id: "5f65ef3c9d06ce06be9947a8", userId: "5f65a0f19d06ce06be9945d8", message: "weds", datetime: "2020-09-19T11:45:00.441Z", user: {…}}
1: {_id: "5f65ef839d06ce06be9947ab", userId: "5f65a0f19d06ce06be9945d8", message: "jgfh", datetime: "2020-09-19T11:46:11.645Z", user: {…}}
2: {_id: "5f65ef879d06ce06be9947ac", userId: "5f65a24c9d06ce06be9945d9", message: "Hello, world!", datetime: "2020-09-19T11:46:15.285Z", user: {…}}
3: {_id: "5f65ef879d06ce06be9947ad", userId: "5f65a0f19d06ce06be9945d8", message: "fgkh", datetime: "2020-09-19T11:46:15.363Z", user: {…}}
4: {_id: "5f65eff19d06ce06be9947af", userId: "5f65a0f19d06ce06be9945d8", message: "erw", datetime: "2020-09-19T11:48:01.906Z", user: {…}}
5: {_id: "5f65f0039d06ce06be9947b2", userId: "5f65a0f19d06ce06be9945d8", message: "yhe", datetime: "2020-09-19T11:48:19.169Z", user: {…}}

С помощью SetInterval() мне нужно вывести новые сообщения, если они есть.

setInterval(() => {
    (async () => {
      let response = await $.get(
        'http://146.185.154.90:8000/blog/botagoz.aimkulova@gmail.com/posts'
      );
      console.log(response)
      let lastDate = response[response.length - 1]['datetime'];
      let newResponse = await $.get(
        `http://146.185.154.90:8000/blog/botagoz.aimkulova@gmail.com/posts?datetime=${lastDate}`
      );
      for (let k in newResponse) {
        showPost(newResponse[k]['user']['firstName'] + ' ' + newResponse[k]['user']['lastName'], newResponse[k]['message']);
      };
    })();
  }, 3000);

Пробовал два варианта указать let lastDate = response[response.length - 1]['datetime']; но тогда сообщения выводяться после перезагрузки страницы, а если

 let lastDate = response[response.length - 2]['datetime'];

то сообщения добавляются по мере поступления, но последнее сообщение добавляется безконечно, пока его место не займет следующее. Подскажите как быть?

1 ответ 1

1
const postsStore = new Set();

let f;
(f = async () => {
  console.log('run...');
  try {
    await handlePosts();
  } catch (err) {
    console.log(err);
  }
  setTimeout(f, 3000);
})();

async function handlePosts() {
  const posts = await apiPosts();
  for (const post of posts) {
    if (!postsStore.has(post._id)) {
      postsStore.add(post._id);
      showPost(post);
    }
  }
}

async function apiPosts() {
  const res = await fetch('http://146.185.154.90:8000/blog/botagoz.aimkulova@gmail.com/posts');
  return res.json();
}

function showPost(post) {
  console.log(
    post.user.firstName,
    post.user.lastName,
    post.message
  );
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.