首页 > 解决方案 > 无法从函数返回

问题描述

我有一个看起来像下面的函数

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 消息出现,但返回语句未定义。

任何帮助,将不胜感激。

标签: javascriptreactjs

解决方案


您不能从回调函数返回,因为它是异步运行的,您无需等待它准备好结果。

但是,您可以通过返回 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');
    });

  }, []);

推荐阅读