【问题标题】:Await promise without continue execution等待承诺而不继续执行
【发布时间】:2020-06-24 15:22:15
【问题描述】:

我有一部分代码可以检索连接到 PC 的一些硬件设备。我还使用 3rd 方库来检索这些设备。我是这样做的:

console.log("before");
// some code here 
(async () => {
  await 3dpartlibrary.getDevices().then(function (myDevices) {  
    for (var i = 0; i < myDevices.length; i++) {
      console.log(myDevices[i]); // i need this information to continue execution
    }
  });
})();
// here i would have a list of devices and i choose one from the list
console.log("after");

但执行仍在继续,一段时间后我收到了控制台消息。 实际上我在控制台中有消息:之前,之后,然后是设备。

因为不能放在函数的顶部,所以我用这种方式放置了异步。

可能是异步等待承诺解决,但下面的代码正在前进,我会在前往 console.log("after") 点之前获取我的列表。

如何等待获得设备列表才能继续执行?

【问题讨论】:

  • 调用匿名异步函数的代码是什么?
  • “我怎样才能在执行该代码之前停止执行?” 将所有剩余代码放在await ... 语句之后。就像现在一样,async/await 部分没用了。您的代码的行为与您刚刚编写的3dpartlibrary.getDevices().then(function (myDevices) { ... }) 完全相同。你想要的大概是:(async () =&gt; { const myDevices = await 3dpartlibrary.getDevices(); for (...) { ... }; /* all the other code */ })();
  • 您无法停止执行。这感觉就像XY-problem。你想达到什么目的?
  • @3limin4t0r 我必须等待下面有要使用的设备列表
  • @52d6c6af 它的顺序代码,在这一点上,我将有一个来自客户端系统的设备列表,然后才能继续

标签: javascript promise async-await


【解决方案1】:
(async () => {
  let myDevices = await 3dpartlibrary.getDevices() 
  myDevices.forEach(console.log)
})();

【讨论】:

  • 虽然这样更好,但我认为它不能解决 OP 的问题。
  • 这会等3dpartlibrary.getDevices(),这不是他想要的吗?
  • 注意,这会将console.log的索引和数组参数也传递给forEach()的回调。
  • 会的,但这就是他们的代码已经在做的事情(以一种不太优雅的方式)。我假设在应该“等待”的异步函数之后还有其他代码。
  • @Patrick True,但我猜他只是在使用 console.log 进行测试,并且他会有一个他会调用的函数。
猜你喜欢
  • 1970-01-01
  • 2020-06-14
  • 2021-05-21
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 2018-10-02
相关资源
最近更新 更多