Продолжайте получать неопределенный результат от нового обещания - PullRequest
0 голосов
/ 16 июня 2020

const randomIntegerFromInterval = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min);
};

const makeTransaction = (transaction) =>
  new Promise((res, rej) => {
    const delay = randomIntegerFromInterval(200, 500);
    setTimeout(() => {
      const canProcess = Math.random() > 0.3;
      if (canProcess) {
        res(transaction.id, randomIntegerFromInterval(200, 500));
      } else {
        rej(transaction.id);
      }
    }, delay);
  });

const logSuccess = (id, time) => {
  console.log(`Transaction ${id} processed in ${time}ms`);
};

const logError = (id) => {
  console.warn(`Error processing transaction ${id}. Please try again later.`);
};

makeTransaction({ id: 70, amount: 150 }).then(logSuccess).catch(logError);

makeTransaction({ id: 71, amount: 230 }).then(logSuccess).catch(logError);

makeTransaction({ id: 72, amount: 75 }).then(logSuccess).catch(logError);

makeTransaction({ id: 73, amount: 100 }).then(logSuccess).catch(logError);

По какой-то причине я все время получаю неопределенное значение. Не могу понять, почему это происходит.

результат должен быть примерно таким. Объясните, в чем проблема, или что мне следует изменить.

task_3.js:23 Error processing transaction 73. Please try again later.
task_3.js:19 Transaction 70 processed in 458ms
task_3.js:19 Transaction 72 processed in 354ms
task_3.js:23 Error processing transaction 71. Please try again later.

Ответы [ 2 ]

1 голос
/ 16 июня 2020

Это потому, что обратные вызовы функций исполнителя res и rej принимают только один параметр. Вам нужно изменить его на что-то вроде этого:

const randomIntegerFromInterval = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min);
};

const makeTransaction = (transaction) =>
  new Promise((res, rej) => {
    const delay = randomIntegerFromInterval(200, 500);
    setTimeout(() => {
      const canProcess = Math.random() > 0.3;
      if (canProcess) {
        res({id: transaction.id, time: randomIntegerFromInterval(200, 500)});
      } else {
        rej(transaction.id);
      }
    }, delay);
  });

const logSuccess = ({id, time}) => {
  console.log(`Transaction ${id} processed in ${time}ms`);
};

const logError = (id) => {
  console.warn(`Error processing transaction ${id}. Please try again later.`);
};

makeTransaction({ id: 70, amount: 150 }).then(logSuccess).catch(logError);

makeTransaction({ id: 71, amount: 230 }).then(logSuccess).catch(logError);

makeTransaction({ id: 72, amount: 75 }).then(logSuccess).catch(logError);

makeTransaction({ id: 73, amount: 100 }).then(logSuccess).catch(logError);

Для справки см. this :

Сигнатуры этих двух функций просты, они принимают один параметр любого типа.

1 голос
/ 16 июня 2020

Разрешите такое обещание

res({
  id: transaction.id, 
  time: randomIntegerFromInterval(200, 500)
});

и запишите вот так

const logSuccess = ({id, time}) => {
  console.log(`Transaction ${id} processed in ${time}ms`);
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...