Home > front end >  How to return a string (or JSON object) from a TypeScript function?
How to return a string (or JSON object) from a TypeScript function?

Time:04-26

The following TypeScript function will retrieve data from a web API and display it to the console from within the function, but when I try to return the data object (a string) I get an error. I am trying to return the JSON data object by return data; but the compiler thinks I am not returning anything. Please, what am I doing wrong?

async function main(url: string, query: string): Promise<string> {

  const axios = require('axios');
  axios.get(url, {params: {"query": query}})
  .then(function (response: any) {
    let data = JSON.stringify(response.data);
    console.log("data: "   data);
    return data;
  })
  .catch(function (error: any) {
    console.log(error);
    return "error";
  });

}

var url: string = 'https://api.subquery.network/sq/AcalaNetwork/karura-tokens';
var query = "{accountBalances (first: 5) {nodes{id accountId tokenId total}}}"
var res = main(url, query).catch(e => console.error(e)).finally(() => process.exit(0))
console.log("res:"   res);

Here is the output:

src/index.ts:1:50 - error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

1 async function main(url: string, query: string): Promise<string> {

In my example I am trying to return a string, but I am happy returning either a string or a JSON object. I just can't get either one to work.

CodePudding user response:

One possible solution (a bit hacky) is to return the promise from your function, declare your res variable in the global scope and, in the promise callback, assign the value the promise resolves to res.

But the actual assignment will only happen after the promise resolves, so you might set a timeout to use the variable outside the promise callback.

For example:

function get_sq(url: string, query: string): Promise<any>{
  const axios = require('axios');
  return axios.get(url, {params: {"query": query}});
}

var url: string = 'https://api.subquery.network/sq/AcalaNetwork/karura-tokens';
var query = "{accountBalances (first: 5) {nodes{id accountId tokenId total}}}"
var res;

get_sq(url, query).then(function (response: any) {
  res = JSON.stringify(response.data);
}).catch(function (error: any) {
  res = error;
});
  

setTimeout(() => {console.log("res:"   res);}, 3000);

Another possibility (the more robust one) is to keep inside the promise callback and do what you want to do with res there.

  • Related