定义一个等待承诺 returns 的 NavigationInstruction

Define an NavigationInstruction that waits until a promise returns

我们如何定义一个等待承诺的 NavigationInstruction returns?

let loginRedirectRoute: RouteConfig = {
    name: "openIdRedirectRoute",
    navigationStrategy: (instruction: NavigationInstruction) => {
        this.loginRedirectHandler().then(() => {
            instruction.config.moduleId = openIdConfiguration.LoginRedirectModuleId;
        }).catch((err) => {
            console.error(err.message);
        });
    },
    route: this.getPath(openIdConfiguration.UserManagerSettings.redirect_uri),
};

以上方法无效。它仅在我们同步调用 instruction.config.moduleId... 时有效。

换句话说,我们需要一个在 promise 之后做某事的导航策略 returns。

这可能吗?如何?

您的内部函数未返回 Promise。尝试

this.loginRedirectHandler().then(() => {
    return instruction.config.moduleId = openIdConfiguration.LoginRedirectModuleId;
}).catch((err) => {
    console.error(err.message);
});

记住

  • .then(() => { return do_this(); }) 链接一个 Promise,
  • .then(() => do_this()); 链接一个 Promise,
  • .then(() => { do_this(); }) 没有。

var foo = 0;

function do_this(bar) {
  console.log("call " + foo + " passed " + bar);
  foo++;
  bar++;
  return bar;
}

var promise = new Promise(function(resolve, reject) {
  window.setTimeout(() => {
    resolve(0);
  }, 500);
});

promise
  .then((bar) => { return do_this(bar); }) /* 1 */
  .then((bar) => do_this(bar)) /* 2 */
  .then((bar) => { do_this(bar); }) /* 3 */
  .then((bar) => do_this(bar)); /* undefined */