简体   繁体   English

Javascript - 异步 function 异步 function 不等待答案?

[英]Javascript - async function in async function doesn't wait for answer?

Problem问题

async function in async function doesn't wait?异步 function 中的异步 function 不等待?

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()) facebook SDK (FB.ui())

I need to get proper value of resFb which waits for async function.我需要获取等待异步 function 的 resFb 的正确值。

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... FB.ui()没有返回 promise,所以Fb()返回的 promise 会立即解析,传递给FB.ui的回调稍后仍会执行...

To return a promise that only resolves when that callback is executed, promisify FB.ui :要返回仅在执行该回调时才解析的 promise,请承诺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)
    )
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM