функция async / await возвращает неопределенное значение? - PullRequest
1 голос
/ 17 апреля 2019

Ниже приведена часть моей функции, которая должна выполняться асинхронно. почему в месте с комментариями оно не определено, так как функция возвращает значение. И если мой код неверен, могу ли я посмотреть, как он должен выглядеть правильно?

    async function addAvailableFunds(
        recipientAvailableFunds,
        amountMoney,
        recipientId,
        transferCurrencyId,
      ) {
          const convertedAmountMoney = await currencyConversion(
            transferCurrencyId,
            recipientCurrencyId,
            amountMoney,
          );

          console.log(
            'convertedAmountMoney',
            convertedAmountMoney,
          ); // undefined


  async function currencyConversion(
    transferCurrencyId,
    recipientCurrencyId,
    amountMoney,
  ) {
    console.log('transferCurrencyId', transferCurrencyId);
    console.log('recipientCurrencyId', recipientCurrencyId);
    console.log('amountMoney', amountMoney);

    await Currency.findOne({
      where: {
        id: recipientCurrencyId,
      },
    }).then(async isRecipientCurrencyId => {
      if (isRecipientCurrencyId) {
        const mainCurrency = isRecipientCurrencyId.main_currency;
        const recipientCurrencyExchangeRate =
          isRecipientCurrencyId.currency_exchange_rate;

        console.log('mainCurrency', mainCurrency);
        console.log(
          'recipientCurrencyExchangeRate',
          recipientCurrencyExchangeRate,
        );

        await Currency.findOne({
          where: {
            id: transferCurrencyId,
          },
        }).then(isTransferCurrencyId => {
          if (isTransferCurrencyId) {
            const transferCurrencyExchangeRate =
              isTransferCurrencyId.currency_exchange_rate;

            console.log(
              'transferCurrencyExchangeRate',
              transferCurrencyExchangeRate,
            );

            if (mainCurrency) {

              const convertedAmountMoney =
                (amountMoney / transferCurrencyExchangeRate) *
                recipientCurrencyExchangeRate;
              console.log('convertedAmountMoney', convertedAmountMoney);
              return convertedAmountMoney; // return number
            }
          }
        });
      }
    });
  }

console.log возвращает число, поэтому я не знаю, что происходит. console.log возвращает число, поэтому я не знаю, что происходит.

Ответы [ 3 ]

1 голос
/ 17 апреля 2019

Вы смешиваете шаблон Promise then с шаблоном async/await.

Это два разных и несовместимых шаблона кодирования. await возвращает значение, не являющееся обещанием (только в контексте функции async), но then никогда не возвращает ничего, кроме другого обещания.

Либо используйте async/await, либо Promises, но не оба в одной логике.

0 голосов
/ 18 апреля 2019

convertedAmountMoney не определено, потому что ничего не было возвращено в currencyConversion.Вы вернулись в .then внутри какого-то другого обещания, но currencyConversion само по себе ничего не вернуло.

Я исправил ваш код ниже, чтобы полностью перейти на async/await, но есть три else sвам придется справиться с собой, потому что на данный момент вы не знали, что делать дальше.Я добавил три предупреждения для этого.

async function addAvailableFunds(
  recipientAvailableFunds,
  amountMoney,
  recipientId,
  transferCurrencyId,
) {
  const convertedAmountMoney = await currencyConversion(
    transferCurrencyId,
    recipientCurrencyId,
    amountMoney,
  );

  console.log(
    'convertedAmountMoney',
    convertedAmountMoney,
  ); // undefined
}


async function currencyConversion(
  transferCurrencyId,
  recipientCurrencyId,
  amountMoney,
) {
  console.log('transferCurrencyId', transferCurrencyId);
  console.log('recipientCurrencyId', recipientCurrencyId);
  console.log('amountMoney', amountMoney);

  const isRecipientCurrencyId = await Currency.findOne({
    where: {
      id: recipientCurrencyId,
    },
  })
  if (isRecipientCurrencyId) {
    const mainCurrency = isRecipientCurrencyId.main_currency;
    const recipientCurrencyExchangeRate =
      isRecipientCurrencyId.currency_exchange_rate;

    console.log('mainCurrency', mainCurrency);
    console.log(
      'recipientCurrencyExchangeRate',
      recipientCurrencyExchangeRate,
    );

    const isTransferCurrencyId = await Currency.findOne({
      where: {
        id: transferCurrencyId,
      },
    })

    if (isTransferCurrencyId) {
      const transferCurrencyExchangeRate =
        isTransferCurrencyId.currency_exchange_rate;

      console.log(
        'transferCurrencyExchangeRate',
        transferCurrencyExchangeRate,
      );

      if (mainCurrency) {
        const convertedAmountMoney =
          (amountMoney / transferCurrencyExchangeRate) *
          recipientCurrencyExchangeRate;
        console.log('convertedAmountMoney', convertedAmountMoney);
        return convertedAmountMoney; // return number
      }
      console.warn('Will return undefined');
    }
    console.warn('Will return undefined');
  }
  console.warn('Will return undefined');
}
0 голосов
/ 18 апреля 2019

Внутри вашего currencyConversion вы смешиваете два подхода для обработки функций, которые возвращают обещания.

Вы делаете:

await Currency.findOne(...params..).then(...params..);

Хотя вы хотели бы сделать следующее, используя синтаксис async/await:

let isRecipientCurrencyId = await Currency.findOne(...params..);
...rest of the code..

асинхронная функция

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...