【问题标题】:Javascript - async function in async function doesn't wait for answer?Javascript - 异步函数中的异步函数不等待答案?
【发布时间】:2022-01-01 08:25:39
【问题描述】:

问题

异步函数中的异步函数不等待?

代码

// 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())

我需要获取等待异步函数的 resFb 的正确值。

【问题讨论】:

标签: javascript asynchronous async-await facebook-sdk-4.0


【解决方案1】:

FB.ui() 不返回一个promise,所以Fb() 返回的promise 会立即解析,传递给FB.ui 的回调仍然会稍后执行...

要返回仅在执行回调时才解析的承诺,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)
    )
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2019-11-28
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2020-03-24
    相关资源
    最近更新 更多