下面是我必须异步执行的功能的一部分。为什么在注释的地方它是未定义的,因为函数返回一个值。如果我的代码不正确,我能否看到它应该如何正确显示?
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 返回一个数字,所以我不知道发生了什么。
最佳答案
您将 Promise then
模式与 async/await
模式混合在一起。
这是两种不同且不兼容的编码模式。 await
返回一个非 Promise 值(仅在 async
函数的上下文中),但是 then
除了另一个 Promise 之外从不返回任何东西。
要么使用 async/await
要么使用 Promises,但不能在同一逻辑中同时使用。
关于javascript - 异步/等待函数返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55735703/