2

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?

Nick
  • 3,454
  • 6
  • 33
  • 56
  • 1
    _"What do i need to do..."_ - Understand what `async`/`await` are/what they do. – Andreas May 06 '20 at 11:55
  • 3
    This is simply not possible. If `GetData` calls an asynchronous function, that makes it asynchronous. Point. You should make `GetData` and `async function` that returns a promise so that you can use `await`. – Bergi May 06 '20 at 11:56
  • @Bergi - Thank you! That did it, all I had to do was make my `GetData` function async! – Nick May 06 '20 at 12:05
  • An `async` function always returns a Promise. If you write `return counter[0].CurrentValue`, this does not return a simple value, as you could expect, but a _promise_ of that simple value. This is why you see `Value from SP is [object Promise]`. Therefore you need to `await` it. – Jeremy Thille May 06 '20 at 12:22

1 Answers1

1

Make GetData async

async function GetData() {
  let initialValue = await GetCounterFromSharepoint()
  console.log('Value from SP is ' + initialValue);
}
brk
  • 48,835
  • 10
  • 56
  • 78