'Accessing Index From Within Then()
I am using OBS Websockets to connect to multiple OBS instances. As a result, I have a foreach() loop to loop over each instance, and call a connect function. This should connect to OBS and populate a dropdown list for each instance, showing available scenes.
My problem is I need to know which sheet I am on (index is part of the for loop, but because the function is async by the time it completes, the index has moved on:
for(sheetIndex = 0; sheetIndex < 8; sheetIndex++)
{
connect(sheetIndex);
}
function connect(sheetIndex)
{
const obs = new OBSWebSocket();
obs.connect({ address: address })
.then(() => {
console.log(`${name} connected on ${address}`);
// get a list of the scenes
await obs.send("GetSceneList").then((data) => {
console.log("New sheet index: " + sheetIndex);
data.scenes.forEach((scene) => {
var sceneListSelect = document.getElementById("SceneListSheet" + sheetIndex);
var opt = document.createElement("option");
opt.innerHTML = scene.name;
sceneListSelect.appendChild(opt);
}
});
}
The value of sheetIndex is unpredictable within the "then", as the for loop has moved on to the next iteration before the call to GetSceneList completes. How can I pass in the value of sheetIndex in to the "then" function so its value is frozen at the time of calling?
Solution 1:[1]
You need to declare the dependency. If you're using maven add the following to pom.xml
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.0</version>
</dependency>
</dependencies>
Or if you're using gradle, add the following to build.gradle:
dependencies {
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.17.0'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.17.0'
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Melchia |
