Javascript - 异步函数中的异步函数不等待回答?
Javascript - async function in async function doesn't wait for answer?
问题
异步函数中的异步函数不等待?
代码
// 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
}
})
}
我需要获取等待异步函数的 resFb 的正确值。
FB.ui()
没有 return 承诺,因此由 Fb()
编辑的承诺 return 将立即解决,并且传递给 FB.ui
的回调将稍后仍然执行...
对于 return 只有在执行该回调时才解析的承诺,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)
)
);
}
问题
异步函数中的异步函数不等待?
代码
// 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
}
})
}
我需要获取等待异步函数的 resFb 的正确值。
FB.ui()
没有 return 承诺,因此由 Fb()
编辑的承诺 return 将立即解决,并且传递给 FB.ui
的回调将稍后仍然执行...
对于 return 只有在执行该回调时才解析的承诺,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)
)
);
}