【发布时间】:2021-05-03 18:37:44
【问题描述】:
我在 MongoDB 上的操作得到以下结果。
这是订单的结果:
const orders = [{
"price": 20200,
"order_number": "19",
"items": [{
"product": {
"_id": "60373f6e93af7d3e3239b21e",
"title": "bb Set",
"process_time": "10"
},
"quantity": 1,
"price": 19000,
"shipping": 1200,
}],
"createdAt": "2021-04-25T12:27:07.985Z",
},
{
"price": 100,
"order_number": "20",
"items": [{
"product": {
"_id": "60373f6e93af7d3e3239b2op",
"title": "Iron Set",
"process_time": "12"
},
"quantity": 1,
"price": 90,
"shipping": 10,
}],
"createdAt": "2021-04-25T12:27:07.985Z",
}
]
我想将process_time 的天数添加到createdAt 字段并将计算的日期写回process_time。
我就是这样做的:
function getDeliveryTime(process_time, order_date) {
let delivery_time = order_date + 1000 * 3600 * 24 * process_time
return new Date(delivery_time).toLocaleDateString()
}
function updateProcess_time(orders) {
for (const order of orders) {
const createdOrder = order.createdAt
for (const item of order.items) {
item.product.process_time = getDeliveryTime(parseInt(item.product.process_time), new Date(createdOrder).getTime())
console.log(item.product.process_time) // I get the value of the process_time at first iteration but get the value of calculated date in the 2nd iteration.
}
}
return orders
}
问题是一些日期没有计算,只有少数返回计算的日期。但大多数我得到process_time: "Invalid Date"。
我认为问题在于它没有等到所有计算完成后才返回订单。
【问题讨论】:
-
问题可能是
process_time不是数字的字符串表示形式,或者createdAt不是 ISO 8601 日期。也许您的 MongoDB 返回空值? -
我更多的是考虑如何更改代码,以便它等到所有计算完成后再返回。
-
@myadsmail ,将计算部分转移到另一个函数中并使用 aync await 等待计算完成
-
我不知道在这段代码中在哪里使用 async/await。
-
更改了答案,但仍然没有得到答案。
标签: javascript node.js arrays mongodb