問題
異步函式中的異步函式不等待?
代碼
// 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 的正確值。
uj5u.com熱心網友回復:
FB.ui()不回傳promise,所以回傳的promiseFb()會立即決議,傳遞給的回呼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)
)
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363220.html
