javascript - 无法从函数返回
问题描述
我有一个看起来像下面的函数
export const checkForAvailableAgent = (topicId, serviceUrl, serviceId) => {
const serviceInfo = new window.adiaLive.ServiceInfo({
topicId: topicId, // set here the topicId which you want listen for
OnError: e => {
// react to error message (optional)
console.log("error: ", e);
},
OnServiceStateChange: e => {
if (e.ConnectedAdvisers > 0) {
// there are advisers online for given topicId
console.log("studio available");
return true;
} else {
console.log("studio not available");
return false;
}
}
});
serviceInfo.connect(serviceUrl, serviceId);
};
但是,当我以下列方式使用该函数时,return 语句不会返回任何内容
useEffect(() => {
const agent = checkForAvailableAgent(
`sales_${i18n.language}`,
"https://linktoserviceurl",
"serviceid"
);
// console.log("studio available is: ", agent);
}, []);
console.log 消息出现,但返回语句未定义。
任何帮助,将不胜感激。
解决方案
您不能从回调函数返回,因为它是异步运行的,您无需等待它准备好结果。
但是,您可以通过返回 a 而不是实际结果来使函数本身异步,Promise
并等到Promise
准备好结果(例如它是resolved
):
export const checkForAvailableAgent = (topicId, serviceUrl, serviceId) => {
return new Promise((resolve, reject) => {
const serviceInfo = new window.adiaLive.ServiceInfo({
topicId: topicId, // set here the topicId which you want listen for
OnError: e => {
// react to error message (optional)
console.log("error: ", e);
reject(); // reject on failure
},
OnServiceStateChange: e => {
if (e.ConnectedAdvisers > 0) {
// there are advisers online for given topicId
console.log("studio available");
resolve(true); // resolve instead of return
} else {
console.log("studio not available");
resolve(false);
}
}
});
serviceInfo.connect(serviceUrl, serviceId);
})
};
useEffect(() => {
checkForAvailableAgent(
`sales_${i18n.language}`,
"https://linktoserviceurl",
"serviceid"
).then((agent) => { // then callback is called when the promise resolved
console.log("studio available is: ", agent);
}).catch(error => { // catch is called when promise got rejected
console.log('An error happened');
});
}, []);
推荐阅读
- git - 如何在 Windows 中基于文件夹设置和切换两个 Github 账户?
- c# - C# 应用程序测试连接(ping、下载、上传)到 Web 服务
- python - url中的下一个参数未显示但在django中正确打印
- android - 如何使图像适合 CardView 的大小
- aws-lambda - Cloudformation:通过 API GW 集成发现 Lambda 函数的权限无效
- unity3d - 如何在贝塞尔样条曲线上估算行进距离
- ruby - 如何优化 Ruby 方法
- python - 基于元素中文本条件的 Python Selenium Web 驱动程序等待
- python - ValueError: Shape must be rank 1 but is rank 2 when doing tf.einsum('i,j->ij',u ,j)
- reactjs - location.state 在我第二次设置时变为空