0

I did an API connection to get a query result (arrays of arrays). But Im not able to save the result into another variable and use it with some other function I have created. I get a answer of Promise {<Pending>}

Here is the example of the code that works fine when using console.log, and not associated to a variable

client.query('SELECT * FROM "INDIGO MONITORING" LIMIT 2;').then(result => console.log(result.rows)).catch(error => console.log(error));

Result example: good Result when testing with console.log in .then

Here is my attempt to save the result and getting back Promise {<pending>}

let results = client.query('SELECT * FROM "INDIGO MONITORING" LIMIT 2;').then(result => {return result}).catch(error => console.log(error));

Result giving Promise Pending

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • Results will be a promise. Either continue the “then” chain, or use the await keyword inside an async function – evolutionxbox Oct 10 '20 at 13:54
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – evolutionxbox Oct 10 '20 at 13:55

3 Answers3

0

You can do this with await, but this will (of course) block the entire calling function until the promise is completed. Also, you don't need then(result => {return result}), that's the default behavior.

let results = await client.query('SELECT * FROM "INDIGO MONITORING" LIMIT 2;').catch(error => console.log(error));

Note: in order for the above line to work, it must be inside a function declared with async (e.g. async function f() {...}).

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • I don't understand what you mean by "block the entire calling function"? It's an asynchronous call and as such it will not block the calling function right? – Christian Oct 10 '20 at 14:51
  • @Christian no, that's the opposite of what I said. If you use `let x = await func()`, it will block and wait until the promise is completed. It's the entire purpose of `await`, to "wait" for the result. – Marco Bonelli Oct 10 '20 at 14:53
  • The result is awaited yes but a promise is immediately returned so no actual blocking is occurring. The promise will "bubble" up through the call chain right? (All the way to the event loop I guess) – Christian Oct 10 '20 at 15:11
  • @Christian no, the promise is not immediately returned. That's the whole purpose of the `await` keyword. After the promise is completed, `result` will contain the value returned through `resolve()` by the promise. Hence, blocking does happen. Test it yourself in your browser or wherever you like: `function f() { return new Promise(r => setTimeout(() => r(123), 3000)) }; console.log(await f());`. – Marco Bonelli Oct 10 '20 at 15:21
  • I thought the point of `async`/`await` was merely syntactic sugaring async code in order to make it more readable and easier to reason about? If I do `await myAsyncFunc()` or for that matter `myAsyncFunc().then(...)` these lines of code will not block but will provide an execution point for the runtime to continue from once the promise has been resolved. I now realize we have slightly different views on "blocking". Sure, any code after the `await`-ing code won't be executed after the promise has resolved but the program as such will not be blocked. https://jsfiddle.net/p3uh2fra/1/ – Christian Oct 10 '20 at 20:06
  • @Christian oh yes, of course. It's not the entire event loop that is blocked, I didn't mean that. – Marco Bonelli Oct 10 '20 at 20:51
0

I would write it in another way.

 Try{

 Const foo = async () => {
  Let data = await axios.get(<URL>)
  }catch(err){
   Console.log(err)

  }

  }
Edward
  • 55
  • 1
  • 10
0

You can make use of async-await.

const getResults = async() => {
  try {
    const results = await client.query('SELECT * FROM "INDIGO MONITORING" LIMIT 2;');
    return results;
  } catch (err) {
    console.log(err);
    return null;
  }
}

Below I have simulated a sample Promise and ways of handling and processing the response. In both the approaches the promise will be resolved after 500ms.

  • Using .then and .catch

const examplePromise = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Success");
    }, 500)
  })
}

examplePromise().then((res) => {
  console.log(res);
}).catch(err => {
  console.log(err)
});
  • Using async and await. In case of async-await the errors will be handled/caught using try/catch.

const examplePromise = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Success");
    }, 500)
  })
}

const asynAwaitEx = async() => {
  try {
    const res = await examplePromise();
    console.log(res);
  } catch (err) {
    console.log(err);
  }
}

asynAwaitEx();
Nithish
  • 5,393
  • 2
  • 9
  • 24