javascript - 不断从新的 Promise 获得未定义的结果
问题描述
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.
解决方案
像这样解决承诺
res({
id: transaction.id,
time: randomIntegerFromInterval(200, 500)
});
并像这样记录
const logSuccess = ({id, time}) => {
console.log(`Transaction ${id} processed in ${time}ms`);
};
推荐阅读
- haskell - MaybeT 的 runMaybeT 的论点
- flutter-dependencies - 颤振独立性
- flutter - 如何在颤动中设置整个应用程序的背景颜色
- javascript - ajax Success 函数不起作用,dataType 为 json
- embedded - UDR 寄存器始终读取 0xFF
- android - 仅在 Ionic-Android 应用程序启动时触发功能
- c# - LINQ 用于获取每个不同名称的 5 条最新记录
- reactjs - 依赖于多个先前 refetchInterval 查询的串行查询
- python - 在 Python 中检测颜色的最简单方法是什么?
- python - Python 3.8.0 总是从同一目录中的导入中获得 linting 警告或 ModuleNotFoundError