0

I'm learning on how to use Async/Await, and as far as I know it should wait until Await is done with executing and then go on with the code.

However, my code completely stops executing after my Await, this is my method (I'm using Vue):

async register () {
  await this.form.validateFields((err, values) => {
    if (err) {
      return
    }
   alert('this gets executed if err is empty')
  })
  alert('this never gets get executed, why?') 
}

validateFields() is a function of Vue's version of Ant Design, and validates my form input. More about it here, maybe it will help inform any of you.

So what exactly am I doing wrong here?

Grek Json
  • 9
  • 3
  • 1
    `await` primarily works on promises. If the function you call accepts a callback, it likely doesn't return a promise and so `await` has no effect. You can wrap callback based functions to return a promise instead. [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/218196) – Felix Kling May 02 '19 at 22:52
  • It returns an object, so how would I go about solving this? – Grek Json May 02 '19 at 22:54

1 Answers1

2

Async await exists to simplify the syntax for working with promises. If you aren't using promises, then async/await gains you nothing.

It looks like validateFields is using callbacks instead of promises, so you'll need to create your own promise around it. For example:

async register () {
  try {
    const values = await new Promise((resolve, reject) => {
      this.form.validateFields((err, values) => {
        if (err) {
          reject (err);
        } else {
          resolve(values);
        }
      })
    })
    console.log('got values', values);
  } catch (error) {
    console.log('caught an error', error);
  }
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98