1

The following code outputs the result of the promise. However, all my attempts to capture the output of the context.log into a variable have failed.

// Get light configuration
client.listLights('all').then(result => {
    context.log(JSON.stringify(result, null, "\t"));
    myvariable = result;
})

.catch(err => {
    context.log.error('Failure ' + err);
});

context.log(myvariable);

The output on myvariable is undefined.

  • In the answer linked, under "ES2015+: Promises with then()" it shows how you can output the promise, which is exactly what my example is doing. However, it doesn't show how or why setting this same output to a variable doesn't stick. –  Mar 24 '19 at 23:51
  • Your `context.log(myvariable)` executes before the `Promise` from `listLights('all')` resolves. `myvariable` will only have the expected value inside the `then` block, so that's where you should be doing work with it. The linked answer explains how you can write this in a style that looks synchronous using `async/await` syntax. – miyu Mar 25 '19 at 00:00
  • This is my second attempt at JavaScript, and after reading the suggested answer, I still don't understand how to transform the above into that syntax. –  Mar 25 '19 at 00:28
  • it would look something like this: `myvariable = await client.listLights('all')`, then you can `context.log(myvariable)`. Note that the function in which all this code is in needs to be declared with the `async` keyword, for example: `async function myFunctionName(args) {...}`. Also note that this is just syntactic sugar on top of the `.then(...)` syntax – miyu Mar 25 '19 at 00:54
  • 1
    The more modern way to do this would be to use async/await. In that case, your code would look more like this: `const result = await client.listLights('all')` `context.log(JSON.stringify(result, null, "\t"));` `myvariable = result; // Assuming this is declared somewhere else in your code using var or let?` `context.log(myvariable);` – djheru Mar 25 '19 at 06:35

0 Answers0