0

I have the following function in JS which is supposed to read all the entries in a firebase database.

async function getMarket() {

let marketRef = db.ref('/market');
let snapshot = await marketRef.once('value');
return snapshot.val();

}

For some reason when I call this function it returns Promise { <state>: "pending" }. Why is this happening?

ninesalt
  • 4,054
  • 5
  • 35
  • 75
  • Async functions have to return `Promise` because they can't return concrete results immediately - that's a core premise of asynchronous computation. – Dai Jan 15 '18 at 15:05
  • 1
    It sounds like the value of your snapshot is a promise, you'll have to await that as well – Sterling Archer Jan 15 '18 at 15:07
  • 1
    @SterlingArcher `async` functions always return promises, regardless of what's returned within them. – JLRishe Jan 15 '18 at 15:07

1 Answers1

2

An async function returns a Promise. Chain .then() and .catch() to process the returned Promise value

guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    This is using `async/await` syntax, no need to use `then` when you await a promise, usually – Sterling Archer Jan 15 '18 at 15:06
  • @SterlingArcher OP describes calling the function. OP appears to expect a value that is not a `Promise` to be returned from the function. `.then()` and needs to be chained to process the `Promise` value returned from the function – guest271314 Jan 15 '18 at 15:07
  • 1
    Right, which would be fine if it wasn't a promise, but with async await you don't need to use `then` to extract the value (an example from my game https://github.com/RUJodan/Source-React/blob/master/routes/login.js) – Sterling Archer Jan 15 '18 at 15:10
  • 1
    @SterlingArcher You _do_ need `.then` (or another `async` function) if you want to extract the value _returned_ from an `async` function. That is what OP is asking about. In the file you linked to, all of the functions are `async`. – JLRishe Jan 15 '18 at 15:22
  • Right, that's why I should they might have to await the results as well. `then` isn't required when using the async wait syntax is what I'm trying to say. Like in a node server when you make an XHR, you have to `await response.json()` to get the actual json results. We're both on the same page here, just syntactical differences – Sterling Archer Jan 15 '18 at 15:24
  • 1
    @SterlingArcher Have you read the actual question: _" For some reason when I call this function it returns `Promise { : "pending" }`. Why is this happening?"_ ? – guest271314 Jan 16 '18 at 02:02