Assigning the result of an async function to a variable in a synchronous function

Viewed 1714

I have an async function:

async function GetCounterFromSharepoint() {
  let counter = await getSharepointListItems('mylist');

  console.log('Got counter from sharepoint as ' + (await counter[0].CurrentValue));

  return counter[0].CurrentValue;
}

The function works as expected, and the console.log statement prints Got counter from sharepoint as 1500'

I'm trying to call the function from the following function

function GetData(){

let initialValue = GetCounterFromSharepoint()
console.log('Value from SP is ' + initialValue);

/* some other lines*/

}

The console.log statement in this second function outputs Value from SP is [object Promise] and not the 1500 that i expect.

This second console.log statement is also printed before the one in the async function. So i thought if i add a delay before it, it would give it time to resolve. So i first tried:

Using the wait function from developers.google.com

function wait(ms) {
  return new Promise((r) => setTimeout(r, ms));
}

let initialValue = GetCounterFromSharepoint()
wait(2000) < -- /*added this */
console.log('Value from SP is ' + initialValue);

This had no effect. So I tried using Promise.resolve as follows:

using Promise.resolve

console.log('Value from SP is ' + Promise.resolve(initialValue));

This gave the same output of Value from SP is [object Promise]

Using await

let initialValue = await GetCounterFromSharepoint()

This gave an error: use of reserved keyword 'await'

What do i need to do to get this to work, please?

1 Answers

Make GetData async

async function GetData() {
  let initialValue = await GetCounterFromSharepoint()
  console.log('Value from SP is ' + initialValue);
}
Related