gpt4 book ai didi

javascript - 如何从 promise 函数返回值

转载 作者:行者123 更新时间:2023-11-30 06:10:31 26 4
gpt4 key购买 nike

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

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 Action 中调用这个函数:

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

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

最佳答案

如果是这样你可以这样做

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' };
}
};

关于javascript - 如何从 promise 函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59170109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com