【发布时间】:2018-03-20 14:21:42
【问题描述】:
我今天的问题与循环内的承诺有关。在这里,我将放置我的代码,如您所见,它做了一些事情。首先,它在我的所有事件中循环,并将在其中找到的日期拆分为 3 个字段,以将其插入 SQL 数据库。
我总共填写了两张表,一张是日期,一张是实际事件。问题是,当这段代码被执行时,它会一直循环到最后,一次完成所有日期分配,然后开始释放承诺。这使得我的函数插入 x 次相同的日期和事件(其中 x 是我的事件数组的长度)。
现在,为什么会发生这种情况?我为这个问题研究并实现了承诺,但它似乎仍然存在。有人可以向我解释我做错了什么吗?另外,你觉得这段代码有点像“末日金字塔”吗?提前非常感谢!
events.forEach(function (event) {
// Simple date formatting
dayFormatted = event.day.split("_");
year = dayFormatted[0];
month = dayFormatted[1];
day = dayFormatted[2];
// Check if the row already exists ...
SQLCheckTableRow(`day`, year.toString(), month.toString(), day.toString()).then(function (skip) {
// ... if not it skips all this part
if (!skip) {
// Create, if it doesn't exist already, a date table that is going to be connected to all the events and fill it
SQLFillTable(`date, `null, "${year}" , "${month}" , "${day}", null`).then(function () {
let values = []
event.ons.forEach(function (on) {
on.states.forEach(function (event) {
values = [];
values.push(Object.keys(event.data).map(function (key) {
return event.data[key];
}));
SQLFillTable(`event`, values).then();
})
})
})
}
})
})
【问题讨论】:
-
只是调用
.then()不会让任何等待。请记住,promise 仍然是异步的,您不能进行阻塞。 -
@Bergi 那么如何阻塞循环的执行并等待函数返回呢?
-
只有
async/await(withoutforEach) 可以阻止循环的执行。否则使用Promise.all等待多个承诺。 -
@Bergi Hum...我明白了,我将尝试更深入地研究 async/await。我认为它们可以替代承诺
-
不,
await是then调用的语法糖。它仍然建立在承诺之上。