Почему мой массив пустой после .then ()? JavaScript [дубликат]

Если вы используете

if((myC=command[i]) =='H' ||
   (myC=command[i]) =='h' ||
   (myC=command[i]) =='C' ||
   (myC=command[i]) =='c')

, то значение успешного выражения закончится в myC, так как оценка в цепочке «или» останавливается при первом истинном подвыражении.

Если вы сделаете еще один шаг, вы можете получить числовое значение, идентифицирующее подвыражение по индексу.

if(((myC=1), command[i]) =='H' ||
   ((myC=2), command[i]) =='h' ||
   ((myC=3), command[i]) =='C' ||
   ((myC=4), command[i]) =='c')

То же понятие, первая успешная субэкспрессия является последней оценкой и , гарантирует, что для сравнения используется только вторая часть.

1
задан ReactRouter4 20 January 2019 в 07:23
поделиться

1 ответ

Цикл for отправляет запросы, которые асинхронно заполняют sendersArray. Если вы console.log(sendersArray) синхронно после запуска цикла for, он еще не будет заполнен. Вместо цикла for используйте .map и Promise.all для ожидания завершения всех запросов:

exports.getRecipientdata = (req, res) => {
  const userId = req.params.recipientId;
  const sendersArray = [];
  Transaction.findAll({
    where: {
      id_recipient: userId,
    },
  }).then(transactions => {
    return Promise.all(transactions.map(({ id_sender }) => (
      User.findOne({
        where: {
          id: id_sender,
        },
        attributes: ['id', 'name', 'surname'],
        include: [
          {
            model: Transaction,
            where: { id_sender: db.Sequelize.col('user.id') },
            attributes: [
              'amount_money',
              'date_time',
              'transfer_title',
              'id_recipient',
              'id_sender',
            ],
          },
        ],
      })
        .then(sender => {
          sendersArray.push(sender);
        })
        .catch(err => {
          console.log(err);
        })
    )));
  })
  .then(() => {
    res.send(sendersArray);
  });
};

Другая возможность, вместо push обращения к внешней переменной, состоит в используйте массив, созданный Promise.all, и отфильтруйте по логическим значениям, чтобы удалить значения Falsey (поскольку отсутствие возвращаемого значения catch приведет к тому, что undefined будет присутствовать в результате массива Promise.all ):

exports.getRecipientdata = (req, res) => {
  const userId = req.params.recipientId;
  Transaction.findAll({
    where: {
      id_recipient: userId,
    },
  }).then(transactions => {
    return Promise.all(transactions.map(({ id_sender }) => (
      User.findOne({
        where: {
          id: id_sender,
        },
        attributes: ['id', 'name', 'surname'],
        include: [
          {
            model: Transaction,
            where: { id_sender: db.Sequelize.col('user.id') },
            attributes: [
              'amount_money',
              'date_time',
              'transfer_title',
              'id_recipient',
              'id_sender',
            ],
          },
        ],
      })
        .catch(err => {
          console.log(err);
        })
    )));
  })
  .then((sendersArray) => {
    res.send(sendersArray.filter(Boolean));
  });
};
0
ответ дан CertainPerformance 20 January 2019 в 07:23
поделиться
Другие вопросы по тегам:

Похожие вопросы: