Using async/await still returns undefined











up vote
-1
down vote

favorite












I asked recently about the asynchronous in javascript, request-promise module returns undefined. I quite understand it after someone gave the same SO question which is the How do I return the response from an asynchronous call?. I learned a lot which helps me to how properly request an api. But now I encounter the same problem even though I'm using async/await already. I put comments where I'm getting an undefined.



const request = require('request');
const rp = require('request-promise');

const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;

const CONNECTION_STRING = process.env.DB;
const dbName = 'fcc';
const connectionOption = { useNewUrlParser: true };

function StockHandler() {

this.latestWithoutLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);

if (typeof lastPrice === 'string') {
getLikes(ticker, false, (data) => {

let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes
}

return callback({ stockData: stockData });
});
}
} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);

if (typeof firstStockLastPrice === 'string' && typeof secondStockLastPrice === 'string') {
let firstStockLikes = await getLikes(ticker[0], false, (data) => { return data; });
let secondStockLikes = await getLikes(ticker[1], false, (data) => { return data; });

console.log(firstStockLikes); // <--- undefined
console.log(secondStockLikes); // <--- undefined
}

}
};

this.latestWithLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);
console.log(lastPrice);
if (typeof lastPrice === 'string') {
getLikes(ticker, true, (data) => {

let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes + 1
}

return callback({ stockData: stockData });
});
}

} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);
console.log(firstStockLastPrice);
console.log(secondStockLastPrice);
}
};

}

function getLastPrice(ticker) {
let options = {
uri: `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${ticker}&interval=1min&apikey=${process.env.ALPHA_KEY}`,
method: 'GET',
json: true
}

return rp(options)
.then(function(parsedBody){
let latestStockTradeTime = Object.keys(parsedBody[Object.keys(parsedBody)[1]])[0];
let closingPrice = parsedBody[Object.keys(parsedBody)[1]][latestStockTradeTime]['4. close'];
return closingPrice;
})
.catch(function(error){
return error;
})
}

function getLikes(ticker, likeStatus, callback) {
MongoClient.connect(CONNECTION_STRING, connectionOption, (err, client) => {

if (err) callback(err);

const db = client.db(dbName);
const collection = db.collection('stock');

if (!likeStatus) {
try {
collection.findOne(
{ stock: ticker.toUpperCase() },
{ upsert: true },
(err, result) => {
if (result === null) {
collection.insertOne(
{ stock: ticker.toUpperCase(), likes: 0 },
{ upsert: true },
(err, result) => {
return callback(result.ops[0]);
}
);
} else {
return callback(result);
}
}
);
} catch (e) {
return callback({ error: e });
}
}
else {
try {
collection.findOneAndUpdate(
{ stock: ticker.toUpperCase() },
{ $inc : { likes: 1 } },
{ upsert: true, new: true },
(err, data) => {
return callback(data.value);
}
);
} catch (e) {
return callback({ error: e });
}
}

});
};

module.exports = StockHandler;









share|improve this question


















  • 2




    If you want to use async/await then getLikes() needs to return a promise.
    – Mark Meyer
    Nov 20 at 2:46










  • What are the other options just in case I don't want to use async/await ?
    – isemaj
    Nov 20 at 2:49










  • This is a lot of code to review. Basically, what @MarkMeyer said: just like a synchronous function, a function using async/await should return a value if you need to chain it, the difference being an async function() wraps its return value (or error) in a Promise.
    – stealththeninja
    Nov 20 at 2:50










  • Does it mean that any function called inside the async function() needs to use await? Because I'm still confuse especially when I remove the await on that two I'm still getting undefined.
    – isemaj
    Nov 20 at 2:56















up vote
-1
down vote

favorite












I asked recently about the asynchronous in javascript, request-promise module returns undefined. I quite understand it after someone gave the same SO question which is the How do I return the response from an asynchronous call?. I learned a lot which helps me to how properly request an api. But now I encounter the same problem even though I'm using async/await already. I put comments where I'm getting an undefined.



const request = require('request');
const rp = require('request-promise');

const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;

const CONNECTION_STRING = process.env.DB;
const dbName = 'fcc';
const connectionOption = { useNewUrlParser: true };

function StockHandler() {

this.latestWithoutLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);

if (typeof lastPrice === 'string') {
getLikes(ticker, false, (data) => {

let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes
}

return callback({ stockData: stockData });
});
}
} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);

if (typeof firstStockLastPrice === 'string' && typeof secondStockLastPrice === 'string') {
let firstStockLikes = await getLikes(ticker[0], false, (data) => { return data; });
let secondStockLikes = await getLikes(ticker[1], false, (data) => { return data; });

console.log(firstStockLikes); // <--- undefined
console.log(secondStockLikes); // <--- undefined
}

}
};

this.latestWithLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);
console.log(lastPrice);
if (typeof lastPrice === 'string') {
getLikes(ticker, true, (data) => {

let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes + 1
}

return callback({ stockData: stockData });
});
}

} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);
console.log(firstStockLastPrice);
console.log(secondStockLastPrice);
}
};

}

function getLastPrice(ticker) {
let options = {
uri: `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${ticker}&interval=1min&apikey=${process.env.ALPHA_KEY}`,
method: 'GET',
json: true
}

return rp(options)
.then(function(parsedBody){
let latestStockTradeTime = Object.keys(parsedBody[Object.keys(parsedBody)[1]])[0];
let closingPrice = parsedBody[Object.keys(parsedBody)[1]][latestStockTradeTime]['4. close'];
return closingPrice;
})
.catch(function(error){
return error;
})
}

function getLikes(ticker, likeStatus, callback) {
MongoClient.connect(CONNECTION_STRING, connectionOption, (err, client) => {

if (err) callback(err);

const db = client.db(dbName);
const collection = db.collection('stock');

if (!likeStatus) {
try {
collection.findOne(
{ stock: ticker.toUpperCase() },
{ upsert: true },
(err, result) => {
if (result === null) {
collection.insertOne(
{ stock: ticker.toUpperCase(), likes: 0 },
{ upsert: true },
(err, result) => {
return callback(result.ops[0]);
}
);
} else {
return callback(result);
}
}
);
} catch (e) {
return callback({ error: e });
}
}
else {
try {
collection.findOneAndUpdate(
{ stock: ticker.toUpperCase() },
{ $inc : { likes: 1 } },
{ upsert: true, new: true },
(err, data) => {
return callback(data.value);
}
);
} catch (e) {
return callback({ error: e });
}
}

});
};

module.exports = StockHandler;









share|improve this question


















  • 2




    If you want to use async/await then getLikes() needs to return a promise.
    – Mark Meyer
    Nov 20 at 2:46










  • What are the other options just in case I don't want to use async/await ?
    – isemaj
    Nov 20 at 2:49










  • This is a lot of code to review. Basically, what @MarkMeyer said: just like a synchronous function, a function using async/await should return a value if you need to chain it, the difference being an async function() wraps its return value (or error) in a Promise.
    – stealththeninja
    Nov 20 at 2:50










  • Does it mean that any function called inside the async function() needs to use await? Because I'm still confuse especially when I remove the await on that two I'm still getting undefined.
    – isemaj
    Nov 20 at 2:56













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I asked recently about the asynchronous in javascript, request-promise module returns undefined. I quite understand it after someone gave the same SO question which is the How do I return the response from an asynchronous call?. I learned a lot which helps me to how properly request an api. But now I encounter the same problem even though I'm using async/await already. I put comments where I'm getting an undefined.



const request = require('request');
const rp = require('request-promise');

const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;

const CONNECTION_STRING = process.env.DB;
const dbName = 'fcc';
const connectionOption = { useNewUrlParser: true };

function StockHandler() {

this.latestWithoutLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);

if (typeof lastPrice === 'string') {
getLikes(ticker, false, (data) => {

let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes
}

return callback({ stockData: stockData });
});
}
} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);

if (typeof firstStockLastPrice === 'string' && typeof secondStockLastPrice === 'string') {
let firstStockLikes = await getLikes(ticker[0], false, (data) => { return data; });
let secondStockLikes = await getLikes(ticker[1], false, (data) => { return data; });

console.log(firstStockLikes); // <--- undefined
console.log(secondStockLikes); // <--- undefined
}

}
};

this.latestWithLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);
console.log(lastPrice);
if (typeof lastPrice === 'string') {
getLikes(ticker, true, (data) => {

let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes + 1
}

return callback({ stockData: stockData });
});
}

} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);
console.log(firstStockLastPrice);
console.log(secondStockLastPrice);
}
};

}

function getLastPrice(ticker) {
let options = {
uri: `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${ticker}&interval=1min&apikey=${process.env.ALPHA_KEY}`,
method: 'GET',
json: true
}

return rp(options)
.then(function(parsedBody){
let latestStockTradeTime = Object.keys(parsedBody[Object.keys(parsedBody)[1]])[0];
let closingPrice = parsedBody[Object.keys(parsedBody)[1]][latestStockTradeTime]['4. close'];
return closingPrice;
})
.catch(function(error){
return error;
})
}

function getLikes(ticker, likeStatus, callback) {
MongoClient.connect(CONNECTION_STRING, connectionOption, (err, client) => {

if (err) callback(err);

const db = client.db(dbName);
const collection = db.collection('stock');

if (!likeStatus) {
try {
collection.findOne(
{ stock: ticker.toUpperCase() },
{ upsert: true },
(err, result) => {
if (result === null) {
collection.insertOne(
{ stock: ticker.toUpperCase(), likes: 0 },
{ upsert: true },
(err, result) => {
return callback(result.ops[0]);
}
);
} else {
return callback(result);
}
}
);
} catch (e) {
return callback({ error: e });
}
}
else {
try {
collection.findOneAndUpdate(
{ stock: ticker.toUpperCase() },
{ $inc : { likes: 1 } },
{ upsert: true, new: true },
(err, data) => {
return callback(data.value);
}
);
} catch (e) {
return callback({ error: e });
}
}

});
};

module.exports = StockHandler;









share|improve this question













I asked recently about the asynchronous in javascript, request-promise module returns undefined. I quite understand it after someone gave the same SO question which is the How do I return the response from an asynchronous call?. I learned a lot which helps me to how properly request an api. But now I encounter the same problem even though I'm using async/await already. I put comments where I'm getting an undefined.



const request = require('request');
const rp = require('request-promise');

const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;

const CONNECTION_STRING = process.env.DB;
const dbName = 'fcc';
const connectionOption = { useNewUrlParser: true };

function StockHandler() {

this.latestWithoutLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);

if (typeof lastPrice === 'string') {
getLikes(ticker, false, (data) => {

let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes
}

return callback({ stockData: stockData });
});
}
} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);

if (typeof firstStockLastPrice === 'string' && typeof secondStockLastPrice === 'string') {
let firstStockLikes = await getLikes(ticker[0], false, (data) => { return data; });
let secondStockLikes = await getLikes(ticker[1], false, (data) => { return data; });

console.log(firstStockLikes); // <--- undefined
console.log(secondStockLikes); // <--- undefined
}

}
};

this.latestWithLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);
console.log(lastPrice);
if (typeof lastPrice === 'string') {
getLikes(ticker, true, (data) => {

let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes + 1
}

return callback({ stockData: stockData });
});
}

} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);
console.log(firstStockLastPrice);
console.log(secondStockLastPrice);
}
};

}

function getLastPrice(ticker) {
let options = {
uri: `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${ticker}&interval=1min&apikey=${process.env.ALPHA_KEY}`,
method: 'GET',
json: true
}

return rp(options)
.then(function(parsedBody){
let latestStockTradeTime = Object.keys(parsedBody[Object.keys(parsedBody)[1]])[0];
let closingPrice = parsedBody[Object.keys(parsedBody)[1]][latestStockTradeTime]['4. close'];
return closingPrice;
})
.catch(function(error){
return error;
})
}

function getLikes(ticker, likeStatus, callback) {
MongoClient.connect(CONNECTION_STRING, connectionOption, (err, client) => {

if (err) callback(err);

const db = client.db(dbName);
const collection = db.collection('stock');

if (!likeStatus) {
try {
collection.findOne(
{ stock: ticker.toUpperCase() },
{ upsert: true },
(err, result) => {
if (result === null) {
collection.insertOne(
{ stock: ticker.toUpperCase(), likes: 0 },
{ upsert: true },
(err, result) => {
return callback(result.ops[0]);
}
);
} else {
return callback(result);
}
}
);
} catch (e) {
return callback({ error: e });
}
}
else {
try {
collection.findOneAndUpdate(
{ stock: ticker.toUpperCase() },
{ $inc : { likes: 1 } },
{ upsert: true, new: true },
(err, data) => {
return callback(data.value);
}
);
} catch (e) {
return callback({ error: e });
}
}

});
};

module.exports = StockHandler;






javascript node.js asynchronous






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 2:44









isemaj

155




155








  • 2




    If you want to use async/await then getLikes() needs to return a promise.
    – Mark Meyer
    Nov 20 at 2:46










  • What are the other options just in case I don't want to use async/await ?
    – isemaj
    Nov 20 at 2:49










  • This is a lot of code to review. Basically, what @MarkMeyer said: just like a synchronous function, a function using async/await should return a value if you need to chain it, the difference being an async function() wraps its return value (or error) in a Promise.
    – stealththeninja
    Nov 20 at 2:50










  • Does it mean that any function called inside the async function() needs to use await? Because I'm still confuse especially when I remove the await on that two I'm still getting undefined.
    – isemaj
    Nov 20 at 2:56














  • 2




    If you want to use async/await then getLikes() needs to return a promise.
    – Mark Meyer
    Nov 20 at 2:46










  • What are the other options just in case I don't want to use async/await ?
    – isemaj
    Nov 20 at 2:49










  • This is a lot of code to review. Basically, what @MarkMeyer said: just like a synchronous function, a function using async/await should return a value if you need to chain it, the difference being an async function() wraps its return value (or error) in a Promise.
    – stealththeninja
    Nov 20 at 2:50










  • Does it mean that any function called inside the async function() needs to use await? Because I'm still confuse especially when I remove the await on that two I'm still getting undefined.
    – isemaj
    Nov 20 at 2:56








2




2




If you want to use async/await then getLikes() needs to return a promise.
– Mark Meyer
Nov 20 at 2:46




If you want to use async/await then getLikes() needs to return a promise.
– Mark Meyer
Nov 20 at 2:46












What are the other options just in case I don't want to use async/await ?
– isemaj
Nov 20 at 2:49




What are the other options just in case I don't want to use async/await ?
– isemaj
Nov 20 at 2:49












This is a lot of code to review. Basically, what @MarkMeyer said: just like a synchronous function, a function using async/await should return a value if you need to chain it, the difference being an async function() wraps its return value (or error) in a Promise.
– stealththeninja
Nov 20 at 2:50




This is a lot of code to review. Basically, what @MarkMeyer said: just like a synchronous function, a function using async/await should return a value if you need to chain it, the difference being an async function() wraps its return value (or error) in a Promise.
– stealththeninja
Nov 20 at 2:50












Does it mean that any function called inside the async function() needs to use await? Because I'm still confuse especially when I remove the await on that two I'm still getting undefined.
– isemaj
Nov 20 at 2:56




Does it mean that any function called inside the async function() needs to use await? Because I'm still confuse especially when I remove the await on that two I'm still getting undefined.
– isemaj
Nov 20 at 2:56












1 Answer
1






active

oldest

votes

















up vote
1
down vote













If you're defining a function with asynchronous behavior, you can use async/await or Promise chaining. Inside an async function, you can use await or chain .then() to wait for asynchronous responses. Your function returns a Promise with the resolved value or error to its callers.



async function getLikes() {
const likes = await db.get('myLikes'); // this db method returns a Promise
// ...
return likes; // will return a Promise resolving likes from db or an error if there is one
}

async function logLikes() {
const result = await getLikes();
console.log(result);
}


If you're consuming an asynchronous function and do not await or chain the response like in this example...



async function getLikes() {
const likes = db.get('myLikes'); // uh oh, this is asynchronous
// ...
return likes;
}


... the thread can move on before the return value is assigned to like. That may be where you're seeing undefined issues.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53385477%2fusing-async-await-still-returns-undefined%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













    If you're defining a function with asynchronous behavior, you can use async/await or Promise chaining. Inside an async function, you can use await or chain .then() to wait for asynchronous responses. Your function returns a Promise with the resolved value or error to its callers.



    async function getLikes() {
    const likes = await db.get('myLikes'); // this db method returns a Promise
    // ...
    return likes; // will return a Promise resolving likes from db or an error if there is one
    }

    async function logLikes() {
    const result = await getLikes();
    console.log(result);
    }


    If you're consuming an asynchronous function and do not await or chain the response like in this example...



    async function getLikes() {
    const likes = db.get('myLikes'); // uh oh, this is asynchronous
    // ...
    return likes;
    }


    ... the thread can move on before the return value is assigned to like. That may be where you're seeing undefined issues.






    share|improve this answer

























      up vote
      1
      down vote













      If you're defining a function with asynchronous behavior, you can use async/await or Promise chaining. Inside an async function, you can use await or chain .then() to wait for asynchronous responses. Your function returns a Promise with the resolved value or error to its callers.



      async function getLikes() {
      const likes = await db.get('myLikes'); // this db method returns a Promise
      // ...
      return likes; // will return a Promise resolving likes from db or an error if there is one
      }

      async function logLikes() {
      const result = await getLikes();
      console.log(result);
      }


      If you're consuming an asynchronous function and do not await or chain the response like in this example...



      async function getLikes() {
      const likes = db.get('myLikes'); // uh oh, this is asynchronous
      // ...
      return likes;
      }


      ... the thread can move on before the return value is assigned to like. That may be where you're seeing undefined issues.






      share|improve this answer























        up vote
        1
        down vote










        up vote
        1
        down vote









        If you're defining a function with asynchronous behavior, you can use async/await or Promise chaining. Inside an async function, you can use await or chain .then() to wait for asynchronous responses. Your function returns a Promise with the resolved value or error to its callers.



        async function getLikes() {
        const likes = await db.get('myLikes'); // this db method returns a Promise
        // ...
        return likes; // will return a Promise resolving likes from db or an error if there is one
        }

        async function logLikes() {
        const result = await getLikes();
        console.log(result);
        }


        If you're consuming an asynchronous function and do not await or chain the response like in this example...



        async function getLikes() {
        const likes = db.get('myLikes'); // uh oh, this is asynchronous
        // ...
        return likes;
        }


        ... the thread can move on before the return value is assigned to like. That may be where you're seeing undefined issues.






        share|improve this answer












        If you're defining a function with asynchronous behavior, you can use async/await or Promise chaining. Inside an async function, you can use await or chain .then() to wait for asynchronous responses. Your function returns a Promise with the resolved value or error to its callers.



        async function getLikes() {
        const likes = await db.get('myLikes'); // this db method returns a Promise
        // ...
        return likes; // will return a Promise resolving likes from db or an error if there is one
        }

        async function logLikes() {
        const result = await getLikes();
        console.log(result);
        }


        If you're consuming an asynchronous function and do not await or chain the response like in this example...



        async function getLikes() {
        const likes = db.get('myLikes'); // uh oh, this is asynchronous
        // ...
        return likes;
        }


        ... the thread can move on before the return value is assigned to like. That may be where you're seeing undefined issues.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 4:05









        stealththeninja

        1,68211325




        1,68211325






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53385477%2fusing-async-await-still-returns-undefined%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'