Async function returning existing array as undefined

Async function returning existing array as undefined

Content Index :

Async function returning existing array as undefined
Tag : javascript , By : Felix Almeida
Date : January 11 2021, 03:32 PM

wish of those help I have an async function inside my class that does execute like it is supposed, but its return value is undefined when I call it. Executing console.log(array) just before the return line "return array" does work , you have to return something from the async function,
// wait for response
return await fetch("https://api.purecore.io/rest/1/session/get/?key=" + this.key, { method: "GET" }).then(function (response) {
class Core {
    constructor(key) {
        this.key = key;
    async getSessions() {
        var finalresponse = []
        try {
            // wait for response
            return await fetch("https://api.purecore.io/rest/1/session/get/?key=" + this.key, { method: "GET" }).then(function (response) {
                return response.json();
            }).then(function (jsonresponse) {
                // looks for errors
                if (jsonresponse.error != null) {
                    throw new Error("PureCore returned an error: " + jsonresponse.error + " -> " + jsonresponse.msg)
                } else {
                    // adds the sessions to the response
                    jsonresponse.forEach(player => {
                        finalresponse.push(new CoreSession(player["mojang_username"], player["mojang_uuid"], player["core_id"], player["verified"]))
                    console.log(finalresponse) // returns array list
                    return finalresponse; // returns undefined
        } catch (e) {
            throw new Error("Error while getting the response for 'https://api.purecore.io/rest/1/session/get/?key=" + this.key + "' -> " + e.message)

class CoreSession {
    constructor(username, uuid, core_uuid, verified) {
        this.username = username;
        this.uuid = uuid;
        this.core_uuid = core_uuid;
        this.verified = verified;

// testing:
sessions = new Core("731b59d106ea5acd0a385958d8e0f18b4b74b741f28f6efa43ed4a273a42d6f9").getSessions().then(function (value) {
}, function (reason) {

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Inside async function, returning value from a callback function returns Promise(undefined)

Tag : javascript , By : Florian D.
Date : March 29 2020, 07:55 AM
will be helpful for those in need I'm new to asynchronous programming, I'm facing issue similar to this question, in this question suggested approach uses callbacks but I'm trying to do it using Promises and async-await functions. I get undefined in the console. Here's my example. what am I missing? , make your query function return a Promise
function query(sql, args) {
    return new Promise(function (resolve , reject) {
        this.connection.query(sql, args, (err, rows) => {
            if (err)

//calling the function here 
query("select 1")
.then((row) => console.log("Rows",row)) // Rows undefined
.catch((e) => console.log(e));

function keeps returning undefined array using Async Await

Tag : javascript , By : Ari
Date : March 29 2020, 07:55 AM
it helps some times The way to return the promise is not by adding new Promise (which is an anti-pattern in this case), but to get the promise that jQuery already has for you:
    return $.getJSON(url, function(data) {
//  ^^^^^^
       // .......
//    ^^^^^^^^^^
    return $.getJSON(url).then(function(data) {
//  ^^^^^^               ^^^^^^
       // .......
       return levels;

Async function is returning undefined

Tag : javascript , By : Helpful Dude
Date : March 29 2020, 07:55 AM
it should still fix some issue You do not return anything from your openChat function, so that function resolves to undefined.
You have to write:
export async function openChat(otherPersonId) {
  const user = firebase.auth().currentUser
  const userId = user.uid

  return firestore // here you need to return the returned promise of the promise chain
    /* .... */
async getChatId(userId) {
  let chatId = await openChat(userId)
  console.log('chatId', chatId) //UNDEFINED
  return chatId

async requestChat(userId) {
  let result = await this.getChatId(userId)
  console.log('result', result) //UNDEFINED

Async function returning undefined instead of data

Tag : javascript , By : Ari
Date : March 29 2020, 07:55 AM
With these it helps I'm doing requests to my API server to authenticate a user, that's not the problem. The problem is that I don't know why my async function doesn't return anything, and I get an error because the data that I want from this function is undefined. , Your Async function must return the last promise:
return fetch('http://api.myapi.cc/authenticate', ...);
var x = await fetch('http://api.myapi.cc/authenticate', ...);
// do something with x and...
return x;
function a() {
    return functionReturningPromise().then(function (result) {
        return result + 1;

async function b() {
    return (await functionReturningPromise()) + 1;

Async function returning undefined in NodeJS

Tag : javascript , By : Raghaw
Date : March 29 2020, 07:55 AM
this one helps. You don't need to use callback function when you use async/await
Try this code:
obtenerCategoria = async(category) => {
    const categoriaDB = await Categoria.findOne({ descripcion: category });
    if (!categoriaDB) {
        return res.status(400).json({
            ok: false,
            msg: 'Categoria no encontrada'
    console.log(categoriaDB); // Works fine here
    return categoriaDB
Related Posts Related QUESTIONS :
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • Call function if variable does not exist in a filter
  • localStorage value doesn't get updated automatically
  • React not updating state with setState correctly inside promises
  • Direct native JavaScript or jQuery method to get containing block of an element
  • Dynamic JSON object to Html Table
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • Interpolated values does not reflect the latest values in an Angular app
  • Javascript classes define attribute in constructor or outside the class
  • How to block scroll event passing through to iframe until iframe is active?
  • What is the purpose of "constructor" method in javascript?
  • Stencil JS not working with non-default imports
  • Are frameworks misleadingly named for marketing purposes?
  • React <Redirect> after transition not working
  • How to send multiple parameters in a function using EJS
  • React conditional style on custom click
  • Push a block of information to an array X times based on an external variable
  • How do I populate dropdown with names, and values (numeric ids)?
  • How to apply styling to elements created with .insertAdjacentHtml method
  • Positioning key:value of an object
  • Referencing DOM Elements with React Hooks
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com