Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Programmatic navigation supports Promise style #2490

Closed
g-plane opened this issue Nov 20, 2018 · 1 comment
Closed

Programmatic navigation supports Promise style #2490

g-plane opened this issue Nov 20, 2018 · 1 comment

Comments

@g-plane
Copy link
Contributor

g-plane commented Nov 20, 2018

What problem does this feature solve?

Currently, a router instance has push and replace methods, and these two methods only support callback style, which they only accept callback as onComplete parameter and onAbort parameter. The push and replace methods themselves will return nothing.

I propose a new API which let push and replace methods return a Promise. This is just like how Vue.prototype.$nextTick behaves.

What does the proposed API look like?

For push and replace methods, if user provide a function as parameter and pass it to onComplete or onAbort parameter, just behave as same as current behavior.

However, if user doesn't provide those parameters, the push and replace should return a Promise like this:

router.push('/')
  .then(/* just do something like in `onComplete` here */)
  .catch(/* just do something like in `onAbort` here */)

This can let us use async/await:

try {
  await router.push('/')
  /* just do something like in `onComplete` here */
} catch {
  /* just do something like in `onAbort` here */
}

In the VueRouter's internal History instance, maybe the push method can be changed to:

push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
  const p = new Promise((resolve, reject) => {
    this.transitionTo(location, route => {
      this.stack = this.stack.slice(0, this.index + 1).concat(route)
      this.index++
      onComplete ? onComplete(route) : resolve(router)
    }, onAbort || reject)
  })
  if (!onComplete && !onAbort) {
    return p
  }
}
@posva
Copy link
Member

posva commented Nov 20, 2018

Duplicate of #1769

@posva posva marked this as a duplicate of #1769 Nov 20, 2018
@posva posva closed this as completed Nov 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants