Home > Back-end >  Javascript - async function in async function doesn't wait for answer?
Javascript - async function in async function doesn't wait for answer?

Time:11-24

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.

CodePudding user response:

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)
    )
  );
}
  • Related