【发布时间】: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 () => { const myDevices = await 3dpartlibrary.getDevices(); for (...) { ... }; /* all the other code */ })(); -
您无法停止执行。这感觉就像XY-problem。你想达到什么目的?
-
@3limin4t0r 我必须等待下面有要使用的设备列表
-
@52d6c6af 它的顺序代码,在这一点上,我将有一个来自客户端系统的设备列表,然后才能继续
标签: javascript promise async-await