J
J
justifycontent2021-01-06 04:28:30
JavaScript
justifycontent, 2021-01-06 04:28:30

Am I building the Promise correctly?

Hello, I approached the study of Promise, please tell me if I built the Promise correctly and can I write it down somehow shorter? Maybe it's possible not to return new Promise every time?
The code:

console.log('Запрос данных...');

const req = new Promise((resolve, reject) => {

    setTimeout(() => {
        console.log('Подготовка данных...');

        const data = {
            name: 'Personal computer',
            model: 'MSI',
            price: 120000,
            weightKG: 10,
        };

        resolve(data);
    }, 2000);
}).then((data) => {
    return new Promise ((resolve, reject) => {

        setTimeout(() => {
            console.log('Обработка данных...');
            data.status = 'order';
            data.discount = '20%';
            data.price -= 120000 * parseInt(data.discount, 10) / 100;

            resolve(data);
        }, 2000);
    });
}).then((data) => {
    return new Promise((resolve, reject) => {

        setTimeout(() => {
            console.log('Выписка чека...');
            data.check = `№${Math.floor(Math.random() * 100000000)}`;

            resolve(data);
        }, 2000);
    });
}).then((data) => {
    return new Promise((resolve, reject) => {

        setTimeout(() => {
            console.log(`Данные получены:\n1.Наименование: ${data.name}\n2.Модель: ${data.model}\n3.Цена: ${data.price}\n4.Вес: ${data.weightKG}\n5.Статус: ${data.status}\n6.Скидка: ${data.discount}\n7.Чек: ${data.check}\n`);
            resolve();
        }, 2000);
    });
}).then(() => {
    setTimeout(() => {
        console.log('...:::С новым годом!:::...');
    }, 2000);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-01-06
@justifycontent

Technically correct, but the basis of programming is the rendering of repetitive actions into functions, conditionally something like this:

function wait(delay) {
  let promise;
  const fn = function(result) {
    return promise || (promise = new Promise(resolve => setTimeout(resolve, delay, result)));
  };
  fn.then = resolve => fn().then(resolve); // использование функции как thennable
  return fn;
}

const req = wait(2000)
.then(() => {
  console.log('Подготовка данных...');

  const data = {
    name: 'Personal computer',
    model: 'MSI',
    price: 120000,
    weightKG: 10,
  };

  return data;
})
.then(wait(2000))
.then(data => {
  console.log('Обработка данных...');
  data.status = 'order';
  data.discount = '20%';
  data.price -= 120000 * parseInt(data.discount, 10) / 100;

  return data;
})
.then(wait(2000))
.then(data => {
  console.log('Выписка чека...');
  data.check = `№${Math.floor(Math.random() * 100000000)}`;

  return data;
})
.then(wait(2000))
.then(data => {
  console.log(`Данные получены:
1.Наименование: ${data.name}
2.Модель: ${data.model}
3.Цена: ${data.price}
4.Вес: ${data.weightKG}
5.Статус: ${data.status}
6.Скидка: ${data.discount}
7.Чек: ${data.check}`);
})
.then(wait(2000))
.then(() => {
  console.log('...:::С новым годом!:::...');
});

It is clear that you have not just setTimeout there, well, you can endure anything.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question