使用我从异步函数中得到的数据。

问题描述 投票:0回答:1

我正在做一个异步网络搜索,可以找到本地网络中所有设备的ip地址。

现在,我想从找到的设备中找到一个特定的ip地址与mac地址匹配。

我的问题是,因为搜索是异步的,所以我不能直接将输出结果保存为一个数组到一个const中,然后在里面搜索特定的mac adress。它总是给我 "promise undefined "的输出。

为了让大家明白,下面是我的代码。

const find = require('local-devices');

async function findIP() {
  // Find all local network devices.
  const found = find().then(devices => {
    console.log(devices);
  })

  await found;

  // here I want to work with the data thats saved inside found and find the ip adress
  console.log(found);
}

findIP();

这段代码的输出是:

    [
  { name: '?', ip: '192.168.0.43', mac: '2a:f2:8c:83:26:8a' },
  { name: '?', ip: '192.168.0.91', mac: '98:da:c4:ff:1c:e1' },
  { name: '?', ip: '192.168.0.152', mac: 'dc:a6:32:01:aa:cc' },
  { name: '?', ip: '192.168.0.175', mac: '00:17:88:65:f4:2d' },
  { name: '?', ip: '192.168.0.182', mac: '4e:98:8d:e5:05:51' },
  { name: '?', ip: '192.168.0.211', mac: '80:be:05:73:bc:g5' }
    ]
Promise { undefined }

所以,实际上我想用 "发现 "数组做的事情是这样的:

  const element = found.find(d => d.mac === '2a:f2:8c:83:26:8a');
  console.log(element ? element.ip : '');

这样我就能得到一个特定mac adress的Ip。但是,如果我把这个放在我的代码中,(而不是把它放在 console.log(found),我得到的是"UnhandledPromiseRejectionWarning: TypeError: found.find is not a function"

那我要把这个放在哪里呢?我找到了一些像这样的等待特定时间的函数,但我不知道在我的代码中把这个函数放在哪里,以便语法正确,并且等待足够长的时间,使承诺不再待定。

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

但我不知道该把这个函数放在哪里 这样语法才是正确的 而且等待的时间也足够长 这样承诺就不会再悬空了

所以基本上我只想告诉我的程序:开始网络搜索,等待5秒,然后将所有找到的设备保存在一个const xy中。之后做 console.log(xy)

我想做的事情可能吗?

javascript asynchronous wait
1个回答
0
投票

你需要从你的承诺中返回一些东西,并且你需要在某个地方分配这个返回值。

const find = require('local-devices');

async function findIP() {
  // Find all local network devices.
  const found = find().then(devices => {
    return devices;
  });
  // you could skip the .then(...) in the above example
  // if you only return what is passed to the .then

  const foundDevices = await found;

  // here I want to work with the data thats saved inside found and find the ip adress
  console.log(foundDevices);
}

findIP();

对于你的具体要求,你可以跳过 .then 堂堂正正 const found = await find();

const find = require('local-devices');

async function findIP() {
  const found = await find();
  const element = found.find(d => d.mac === '2a:f2:8c:83:26:8a');
  console.log(element ? element.ip : '');
}

findIP();
© www.soinside.com 2019 - 2024. All rights reserved.