【问题标题】:how to return value from a promise function如何从 Promise 函数返回值
【发布时间】:2020-03-28 21:46:04
【问题描述】:

我有一个检查设备是否在线的功能。下面是代码。

const ping = require('ping');
export function findDevices(device) {
  try {
    const hosts = [device];
    let result = null;
    hosts.forEach((host) => {
      ping.promise.probe(host)
        .then((res) => {
          console.log(res.alive)
          result = res.alive;
          return {
            Status: result
          }
        });
    });
  } catch (err) {
    logger.error(err, '[ config - findDevices() ]');
    console.error(err);
    return {
      Status: "Failed"
    }
  }
}

我在这样的 redux 操作中调用此函数:

export function start(device) {
  return dispatch => {
    const status = Connectionstatus.findDevices(device);
    return dispatch({
      type: actionTypes.CONNECTIONSTATUS,
      payload: {
        ConnectionStatus: status
      }
    })
  };
}

我希望状态变量为真或假。但是即使我在 promise 函数的 then 中返回值,我也变得未定义。我已尝试等待此电话,但仍然无法正常工作。任何帮助将非常感激。谢谢。

【问题讨论】:

  • 您必须在then() 块之外返回结果。这应该有效。
  • 我也试过了。它返回 null;
  • 为什么你在循环中调用一个promise
  • 如果有多个主机,我应该返回每个主机的状态。这就是为什么。
  • 您可能想查看将hosts 数组映射为所有承诺,并使用Promise.all() 解决它们。

标签: javascript node.js promise async-await


【解决方案1】:

如果是这样,你可以这样做

const getStatus = async () => {
  try {
    const hosts = [device];
    const promises = [];
    hosts.forEach((host) => {
      promises.push(ping.promise.probe(host));
    });
    const result = await Promise.all(promises);
    const status = result.map((r) => { return r.alive; });
    return status;
  } catch (err) {
    logger.error(err, '[ config - findDevices() ]');
    return { status: 'Failed' };
  }
};

【讨论】:

    【解决方案2】:

    不是 100% 确定所有的变量是什么,但您是否考虑过使用 async/await 来简化这样的事情?

    const getStatus122 = async device => {
      return await Promise.all([device].map(ping.promise.probe))
          .then(({ alive }) => alive)
          .then(Status => ({ Status }))
          .catch(error => {
            logger.error(error, '[ config - findDevices() ]');
            return { Status: 'Failed' };
          })
    }
    

    在此处了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    【讨论】:

      【解决方案3】:

      使用 Promises,您应该在 whencatch 回调函数中检查承诺的结果。使用 async/await 代码可能看起来更简单一些。这是带有明确承诺的版本。

      const ping = require('ping');
      const Connectionstatus = {
        findDevices: (device) => {
          return ping.promise.probe(device).then((res) => {
            const result = res.alive;
            console.log(result);
            return {
              Status: result,
            };
          }).catch((err) => {
            logger.error(err, '[ config - findDevices() ]');
            console.error(err);
            return {
              Status: "failed"
            }
          });
        }
      }
      export function start(device) {
        return dispatch => {
          Connectionstatus.
          findDevices(device).
          then((status) => {
            dispatch({
              type: actionTypes.CONNECTIONSTATUS,
              payload: {
                ConnectionStatus: status
              }
            })
          });
        };
      }
      

      您可能会看到错误处理移至catch 回调函数,而调度在then 回调函数中完成。这就是您问题的答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2017-04-08
        • 1970-01-01
        • 2021-11-28
        • 2019-01-09
        • 1970-01-01
        相关资源
        最近更新 更多