为什么在Lightswitch中堆叠承诺的一种方法有效,而另一种方法则不起作用

Why does one method of stacking promises in Lightswitch work when another doesn't?

本文关键字:方法 有效 一种 不起作用 另一种 Lightswitch 承诺 为什么      更新时间:2023-09-26

我正在使用Lightswitch 2015应用程序来跟踪客户满意度访谈。 我正在尝试创建一个函数,该函数将创建一个新的采访,填充一些项目,然后将其保存到数据库中,然后在新窗口中打开它进行编辑。 在这种情况下,我正在努力理解承诺的行为。

我有以下三个代码组:

1(

myapp.Interviews_Management.AddInterview_Tap_execute = function (screen)
{
    var NewInterview = screen.Interviews.addNew();
    NewInterview.c_Date = screen.InterviewDate;
    NewInterview.Participant = screen.Interviewee;
    NewInterview.Location = screen.InterviewFocusLocation;
    screen.closePopup()
    .then(() =>
    {
        myapp.applyChanges()
                .then(() =>{ myapp.showInterview_AddEdit(NewInterview); });
    }, (error) =>{ msls.showMessageBox(error.toString()); });
};

2(

myapp.Interviews_Management.AddInterview_Tap_execute = function (screen)
{
    var NewInterview = screen.Interviews.addNew();
    NewInterview.c_Date = screen.InterviewDate;
    NewInterview.Participant = screen.Interviewee;
    NewInterview.Location = screen.InterviewFocusLocation;
    screen.closePopup()
        .then(myapp.applyChanges()
            .then(myapp.showInterview_AddEdit(NewInterview),
                (error) =>{ msls.showMessageBox(error.toString()); })
            );
};

3(

myapp.Interviews_Management.AddInterview_Tap_execute = function (screen)
{
    var NewInterview = screen.Interviews.addNew();
    NewInterview.c_Date = screen.InterviewDate;
    NewInterview.Participant = screen.Interviewee;
    NewInterview.Location = screen.InterviewFocusLocation;
    screen.closePopup()
        .then(myapp.applyChanges())
        .then(myapp.showInterview_AddEdit(NewInterview),
            (error) =>{ msls.showMessageBox(error.toString()); });
};

1 按预期工作;即,创建新的采访,填充字段,然后打开编辑窗口。 但是,我担心从 lambda 函数内部抛出的错误不会正确传递到外部上下文。

2 和 3 都创建了一个新的采访并填充字段,但随后抛出一个错误,指出"屏幕导航时无法执行此操作",这似乎表明它没有等待每个承诺实现,然后再尝试执行下一个承诺。 3 似乎也可能是将承诺包装在其他承诺中,这可能会再次导致无法正确地向外传递任何抛出的错误(而且,我听说,对于努力理解承诺的人来说,这是一种非常常见的反模式?

有人可以帮助我了解这里到底发生了什么吗? 我一直在努力寻找嵌套承诺或使用一系列承诺的正确最佳实践;任何正确处理此问题的帮助将不胜感激!

你总是需要将回调函数传递给then,而不是立即调用它的结果。

你想要

screen.closePopup()
  .then(myapp.applyChanges) // or () => myapp.applyChanges()
  .then(() => myapp.showInterview_AddEdit(NewInterview)),
  .catch(error => { msls.showMessageBox(error.toString()); });

有关为什么需要该catch(比使用第二个then参数更好(,请参阅 .then(成功,失败(何时被视为承诺的反模式?。