javascript - 在承诺解决之前表达 JS 退出 API
问题描述
在映射中,我有两个将进入的对象default
和switch
1 个将进入ORDER_OPEN
case 的记录,并且该对象不会进入 if 语句,只是它会推送到,orderArray
但是当 API 执行时,我只从default
何时接收两个对象我记录了它在执行 API 后orderArray
正在推送。objectArray
router.get('/orderByPhone/:id', async (req, res) => {
const { ORDER_OPEN, ORDER_FILL, BITY_FILL, BITY_CANCEL, getOrderStatusValue } = require('../../lib/constants/orderStatus');
const statusUtils = require('../../lib/constants/orderStatus');
const apiUtils = require('../../lib/apiUtils');
const neo4jUtils = require('../../lib/neo4jUtils');
const orderArray = [];
try {
const id = req.params.id;
const response = await neo4jUtils.getOrders(1, id);
response.records.map(async (record) => {
switch (record._fields[0].properties.orderStatus) {
case ORDER_OPEN:
const ret = await apiUtils.fetchOrderStatus(record._fields[0].properties.bityId, record._fields[0].properties.token);
if (ret.legacy_status == BITY_FILL) {
await neo4jUtils.updateOrderStatus(record._fields[0].properties.bityId, getOrderStatusValue(ret.legacy_status))
} else if (ret.legacy_status == BITY_CANCEL) {
await neo4jUtils.updateOrderStatus(record._fields[0].properties.bityId, getOrderStatusValue(ret.legacy_status))
}
orderArray.push({
input: {
amount: ret.input.amount,
currency: ret.input.currency
},
ouput: {
amount: ret.output.amount,
currency: ret.output.currency
},
status: {
status: statusUtils.getOrderStatusValue(ret.legacy_status)
}
});
break;
case ORDER_FILL:
orderArray.push({
input: {
amount: record._fields[0].properties.fromAmount,
currency: record._fields[0].properties.fromCurrency
},
ouput: {
amount: record._fields[0].properties.toAmount,
currency: record._fields[0].properties.toCurrency
},
status: {
status: record._fields[0].properties.orderStatus
}
});
break;
default:
orderArray.push({
input: {
amount: record._fields[0].properties.fromAmount,
currency: record._fields[0].properties.fromCurrency
},
ouput: {
amount: record._fields[0].properties.toAmount,
currency: record._fields[0].properties.toCurrency
},
status: {
status: record._fields[0].properties.orderStatus
}
});
break;
}
});
} catch (error) {
res.status(500).send(errorHandleing.FiveZeroZero)
}
res.status(200).json(orderArray);
});
解决方案
response.records.map(async (record) => {...}
wait
是一个同步函数,它会返回一个 promises 数组,你的代码在所有动作{...}
完成之前不会。这是您的请求只需很短的时间即可响应的主要原因。
正确的方法,只是等到所有工作完成:
let promises = response.records.map(async (record) => {...}
await Promise.all(promises); // waiting....
推荐阅读
- python - 如何使用烧瓶 sqlalchemy 使过滤查询更有效?
- typescript - 带有 getter 和 setter 的构造函数属性(私有)
- audio - 防止 SoX 进行剪辑?
- python - 如何将累积数据转换为python中多个索引的每日数据?
- python - 使用“out”参数从 Python 调用 C# DLL
- python - “UnityEnvironment”对象没有属性“behavior_spec”
- vue.js - NuxtJS 内容错误 @nuxtjs/content
- r - R:按不明确的值拆分列中的数据
- r - 数据框和向量之间的布尔比较错误
- android-studio - 没有模拟器的 Android Studio for Dart