Shaun Luttin Shaun Luttin - 3 months ago 7
Javascript Question

Define an NavigationInstruction that waits until a promise returns

How can we define an NavigationInstruction that waits until a promise 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),
};


The above does not work. It only works if we call instruction.config.moduleId... synchronously.

In other words, we need a navigation strategy that does something after a promise returns.

Is this possible? How?

Answer

Your inner function is not returning a Promise. Try

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

Remember that

  • .then(() => { return do_this(); }) chains a Promise,
  • .then(() => do_this()); chains a Promise,
  • .then(() => { do_this(); }) does NOT.

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 */

Comments