-4

I have a part of code to retrieve some hardware device connected to PC. I also use a 3rd party library to retrieve these devices. I have done it in this way:

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");

But the execution continues and I have the console messages after a bit of time. Actually i have in console the messages: before, after, and then devices.

I have put async in this way because cannot put in top of the function.

Probably async wait promise to resolve but the underneath code is goind ahead, i i would to obtain my list befor to go console.log("after") point.

How can I wait to have a list of devices before to continue execution?

Max
  • 87
  • 4
  • 12
  • What is the code surrounding the call to the anonymous async function? – Ben Aston Mar 12 '20 at 14:43
  • 5
    *"How i can stop execution before that code is executed?"* Put all the remaining code after the `await ...` statement. As it is now the `async/await` part is useless. Your code behaves exactly as if you had just written `3dpartlibrary.getDevices().then(function (myDevices) { ... })`. What you want is probably: `(async () => { const myDevices = await 3dpartlibrary.getDevices(); for (...) { ... }; /* all the other code */ })();` – Felix Kling Mar 12 '20 at 14:44
  • 3
    You can't stop execution. This feels like an [XY-problem](http://xyproblem.info/). What are you trying to achieve? – 3limin4t0r Mar 12 '20 at 14:53
  • @3limin4t0r i have to wait for have a list of devices to use underneath – Max Mar 12 '20 at 15:03
  • @52d6c6af its sequencial code, int that point i would have a list of devices from client system, before to continue – Max Mar 12 '20 at 15:04
  • I recommend giving [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) a read. – 3limin4t0r Mar 12 '20 at 15:53

1 Answers1

0
(async () => {
  let myDevices = await 3dpartlibrary.getDevices() 
  myDevices.forEach(console.log)
})();
radulle
  • 1,437
  • 13
  • 19