【发布时间】:2015-10-23 19:36:44
【问题描述】:
我正在尝试以“正确的方式”使用 Promise,但我对这种情况感到困惑。以下是两段代码。第一个完美运行,第二个失败。我认为它们应该以相同的方式工作,但事实并非如此。在两者中,都创建了两条记录,但 isCrawlDue 仅在第一个中找到记录。我有 99% 的把握,错误在于我编写此承诺链的方式,而不是被调用的函数。
这是按预期工作的块。
clearStatements()
.then(dbFinancials.addStatement("XYZ", "type", moment.utc([2014, 0, 31]), 3, "none")
.then(function (added1) {
assert.isTrue(added1, "First record not added.");
dbFinancials.addStatement("XYZ", "type", moment.utc(), 4, "none")
.then(function (added2) {
assert.isTrue(added2, "Second record not added.");
dataCollection.isCrawlDue("XYZ")
.then(function (isDue) {
assert.isTrue(isDue, "No need for a crawl detected.");
done();
});
});
}));
这段代码添加了两个语句,但在isCrawlDue 中,没有找到这两个语句。我知道isCrawlDue 有效,因为它在上面的代码中有效。
clearStatements()
.then(dbFinancials.addStatement("XYZ", "type", moment.utc([2014, 0, 31]), 3, "none"))
.then(dbFinancials.addStatement("XYZ", "type", moment.utc(), 4, "none"))
.then(dataCollection.isCrawlDue("XYZ")
.then(function (isDue) {
assert.isTrue(isDue, "No need for a crawl detected.");
done();
}));
谁能看到我做错了什么?
【问题讨论】:
-
这实际上可能是因为
isCrawlDue尚未定义,这与您的怀疑相反。在您的第一种情况下,标识符isCrawlDue在其包含函数运行之前不会导致引用查找(即function (added2)回调)。在您的第二个示例中,它会立即进行评估。 -
当我输入一些console.log 语句时,我依次得到“add statement”、“add statement”和“isCrawlDue”,表明它们按我预期的顺序发生。也就是说,我不确定这是否与您立即“评估”的说法相矛盾,因为它绝对不像我认为的那样有效。如果我必须嵌套承诺,那不是违背了使用它们的目的吗?他们不是打算克服回调的深层嵌套吗?