Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – async function in async function doesn't wait for answer?

Problem

async function in async function doesn’t wait?

Code

// onConfirmed executes after confirming on modal
onConfirmed={async () => {
  const res = await submit(submitData) // post data and return some data
  if (!res.error) {
    const resFb= await Fb(data)
    console.log(resFb) // ***execute it before waiting "await Fb(data)"
  } else {
  // handle error
  }
}}
//Fb function
export const Fb = async (data) => {
  const body = {
    method: 'share',
    href: 'https://hogehoge',
    display: 'popup',
    hashtag: '#hogehoge',
    quote: `content: ${data.content}`,
  }
  return FB.ui(body, async (res) => {
    if (res !== undefined && !res.error_code) {
      return await Api.put(body) // put to own server (executes here without problem)
    } else {
      return res
    }
  })
}

facebook SDK (FB.ui())

I need to get proper value of resFb which waits for async function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

FB.ui() does not return a promise, so the promise returned by Fb() will resolve immediately, and the callback passed to FB.ui will still execute later…

To return a promise that only resolves when that callback is executed, promisify FB.ui:

export const Fb = (data) => {
  const body = {
    method: 'share',
    href: 'https://hogehoge',
    display: 'popup',
    hashtag: '#hogehoge',
    quote: `content: ${data.content}`,
  };
  return new Promise(resolve => 
    FB.ui(body, res =>
      resolve(!res?.error_code ? Api.put(body) : res)
    )
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading