1

Given I have the following function:

async function foo() {
  document.getElementById('ok').addEventListener('click', () => {
    // How do I resolve from foo here?
  })
  document.getElementById('cancel').addEventListener('click', () => {
    // How do I reject from foo here?
  })
}

As the comment states, how can I resolve or reject foo's promise within the nested function?

My current solution is:

function foo() {
  return new Promise((resolve, reject) => {
    document.getElementById('ok').addEventListener('click', () => {
      resolve()
    })
    document.getElementById('cancel').addEventListener('click', () => {
      reject()
    })
  })
}

But with this, I have to return the Promise myself rather than using async. Is there a better way?

Edit: The example I gave initially was not the best. Updated my question and code.

  • As I know any `return` is a `resolve`, `throw` is a `reject`. The function with `async` will automatically *return a `Promise`* – Loi Nguyen Huynh Dec 23 '19 at 13:27
  • 2
    Without further details, that would be the right way to do it, yes. Async functions aren’t… for that. – Ry- Dec 23 '19 at 13:27

1 Answers1

0

You can return the return value of bar from foo to resolve the promise, or throw from bar, to reject it:

async function foo() {
  const bar = () => {
    return 'Resolved'
    //or `throw 'Rejected'`
  }

  //Where you call `bar`:
  return bar()
}

foo().then(console.log) //Resolved

Edit according to the edit made to the question

You have to promisify all of your asynchronous operations, in order to use them with async/await.

So, you'll need to create a promise like you've done. Then, you can do whatever with that promise.

So, your approach is completely right (the only trivial optimization you can do is to avoid creation of additional handler functions):

function foo() {
  return new Promise((resolve, reject) => {
    document.getElementById('ok').addEventListener('click', resolve)
    document.getElementById('cancel').addEventListener('click', reject)
  })
}
FZs
  • 16,581
  • 13
  • 41
  • 50
  • Dang, my example was sh*t as you are right, I could simply return in bar and use that value to return in foo. My problem is that bar is actually a DOM event handler. I'll update my post. –  Dec 23 '19 at 13:35