0

I'm currently discovering Google Datastore and it seems pretty useful.

However (I'm a JS newbie) I'm stuck with something pretty simple concerning Promise and Async/await, and I'm not able to find my answer (I tried...).

This get works perfectly into my terminal (it's fairly simple):

datastore.get(datastore.key(['viewing', 'abc123']))
.then((slot) => {
  console.log(slot[0])
})

But what I want is to wrap this query into a const and return slot[0] on-demand...

So I've tried:

const wrap = () => {
  datastore.get(datastore.key(['viewing', 'abc123']))
    .then((slot) => {
      return slot[0]
    })
}

Didn't work. I've tried to add a return before datastore.get, to change a return for a Promise.resolve... but it's still the same : Promise pending (best case).

I do not speak about using async/await. I can't return my slot[0]...

Any clue, thanks.

charnould
  • 2,480
  • 3
  • 19
  • 23

1 Answers1

0

What you are dealing with is a promise. The way I always think about it is once you enter "Promise-Land" you can't escape. Some may see that as a bad thing but i think it's great.

Once you run the get, at some point in the future it will finish. When it does it calls the function inside the then and passes it the value. From this point on you have to work inside of then statements. (caveat below)

You can keep a reference to the promise and use it as a value

const omg = datastore.get(datastore.key(['viewing', 'abc123']))

You can only get at the value by using the .then function.

omg.then(console.log)

You can take your value and pass it to another function, whether a lambda:

omg
    .then(slot => slot[0])
    .then(console.log)

or a named function

const head = list => list[0];
omg
    .then(head)
    .then(console.log)

Thats the best way to use promises

If that is too foreign or you aren't used to that type of programming (functional) then you can use the imperative Async/Await.

const omg = await datastore.get(datastore.key(['viewing', 'abc123']))

It should do what you expect but has to be transpiled by babel or similar.

ktilcu
  • 3,032
  • 1
  • 17
  • 15