getting value from a chained promises





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















im really new to this of promises and im getting headaches trying to understand this, so now im trying to get an answer from a method that returns a promise, then i catch the value in a conditional and make some other operations



let addService = async(req, res) => {
checkCategoryExists(param).then(result => {
if(result){
// code here
}
}).catch(err => console.log(err));
}


let checkCategoryExists = async(param) => {
let docs = db.collection(collectionName).doc(param);
docs.get()
.then(categoryDoc => {
if(categoryDoc.exists){
if(categoryDoc.data().param== param){
return true;
}
} else {
return false;
}
})
.catch(err => false);
}


the method "checkCategoryExists" is a query to a firestore db. When i tried to check if result variable is true or false, it happens to be undefined. its not with ".then()" that i get to catch the value from the returned promise? if someone can help me, thanks in advance










share|improve this question























  • i'm pretty sure if you are getting undefined it is because you aren't returning the result of your query should be return docs.get().then.....

    – D Lowther
    Nov 23 '18 at 20:49











  • @DLowther's diagnosis is right. The simple fix is docs.get()...

    – danh
    Nov 24 '18 at 5:41


















0















im really new to this of promises and im getting headaches trying to understand this, so now im trying to get an answer from a method that returns a promise, then i catch the value in a conditional and make some other operations



let addService = async(req, res) => {
checkCategoryExists(param).then(result => {
if(result){
// code here
}
}).catch(err => console.log(err));
}


let checkCategoryExists = async(param) => {
let docs = db.collection(collectionName).doc(param);
docs.get()
.then(categoryDoc => {
if(categoryDoc.exists){
if(categoryDoc.data().param== param){
return true;
}
} else {
return false;
}
})
.catch(err => false);
}


the method "checkCategoryExists" is a query to a firestore db. When i tried to check if result variable is true or false, it happens to be undefined. its not with ".then()" that i get to catch the value from the returned promise? if someone can help me, thanks in advance










share|improve this question























  • i'm pretty sure if you are getting undefined it is because you aren't returning the result of your query should be return docs.get().then.....

    – D Lowther
    Nov 23 '18 at 20:49











  • @DLowther's diagnosis is right. The simple fix is docs.get()...

    – danh
    Nov 24 '18 at 5:41














0












0








0








im really new to this of promises and im getting headaches trying to understand this, so now im trying to get an answer from a method that returns a promise, then i catch the value in a conditional and make some other operations



let addService = async(req, res) => {
checkCategoryExists(param).then(result => {
if(result){
// code here
}
}).catch(err => console.log(err));
}


let checkCategoryExists = async(param) => {
let docs = db.collection(collectionName).doc(param);
docs.get()
.then(categoryDoc => {
if(categoryDoc.exists){
if(categoryDoc.data().param== param){
return true;
}
} else {
return false;
}
})
.catch(err => false);
}


the method "checkCategoryExists" is a query to a firestore db. When i tried to check if result variable is true or false, it happens to be undefined. its not with ".then()" that i get to catch the value from the returned promise? if someone can help me, thanks in advance










share|improve this question














im really new to this of promises and im getting headaches trying to understand this, so now im trying to get an answer from a method that returns a promise, then i catch the value in a conditional and make some other operations



let addService = async(req, res) => {
checkCategoryExists(param).then(result => {
if(result){
// code here
}
}).catch(err => console.log(err));
}


let checkCategoryExists = async(param) => {
let docs = db.collection(collectionName).doc(param);
docs.get()
.then(categoryDoc => {
if(categoryDoc.exists){
if(categoryDoc.data().param== param){
return true;
}
} else {
return false;
}
})
.catch(err => false);
}


the method "checkCategoryExists" is a query to a firestore db. When i tried to check if result variable is true or false, it happens to be undefined. its not with ".then()" that i get to catch the value from the returned promise? if someone can help me, thanks in advance







javascript node.js promise google-cloud-firestore






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 20:47









JeferJefer

156




156













  • i'm pretty sure if you are getting undefined it is because you aren't returning the result of your query should be return docs.get().then.....

    – D Lowther
    Nov 23 '18 at 20:49











  • @DLowther's diagnosis is right. The simple fix is docs.get()...

    – danh
    Nov 24 '18 at 5:41



















  • i'm pretty sure if you are getting undefined it is because you aren't returning the result of your query should be return docs.get().then.....

    – D Lowther
    Nov 23 '18 at 20:49











  • @DLowther's diagnosis is right. The simple fix is docs.get()...

    – danh
    Nov 24 '18 at 5:41

















i'm pretty sure if you are getting undefined it is because you aren't returning the result of your query should be return docs.get().then.....

– D Lowther
Nov 23 '18 at 20:49





i'm pretty sure if you are getting undefined it is because you aren't returning the result of your query should be return docs.get().then.....

– D Lowther
Nov 23 '18 at 20:49













@DLowther's diagnosis is right. The simple fix is docs.get()...

– danh
Nov 24 '18 at 5:41





@DLowther's diagnosis is right. The simple fix is docs.get()...

– danh
Nov 24 '18 at 5:41












1 Answer
1






active

oldest

votes


















0














So as mentioned above I think your issue is based on not returning the results of your document search so both examples below handle that.



I also noticed that you were using async tags on your functions but not ever using await so I wanted to give examples of both ways of doing it in case you wanted to use Async/Await but weren't certain how.



In the promise chain example I'm relying on the syntax of arrow functions to create the returns (no {} means return right side of equation) since none of your given code requires data manipulation before return (if your actual code needs that you should of course use brackets and remember your return statement :D )



If you choose to use Async/Await you can structure the code much more closely to synchronous examples and use try catch statements. Sometimes I find this syntax more clear if I have to do a lot of processing/manipulation before returning a result.



Good Luck :)!






// Promise Chains
const addService = (req, res) =>
checkCategoryExists(param)
.then(result => /* do stuff */)
.catch(err => console.error(err.message));

const checkCategoryExists = param =>
db.collection(collectionName.doc(param)
.get()
.then(categoryDoc =>
Promise.resolve((categoryDoc.exists && categoryDoc.data().param === param))
);

// OR using Async/Await
const addService async (req, res) => {
try {
const catExists = await checkCategoryExists(param);
if (!catExists) {
throw new Error('error code');
}

// Do Stuff.
} catch (error) {
console.error(error);
}
};

const checkCategoryExists = async param => {
try {
const docs = await db.collection(collectionName)
.doc(param)
.get();

return (docs.exists && docs.data().param === param);
} catch (error) {
console.error(error)
}
}








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',
    autoActivateHeartbeat: false,
    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%2f53452778%2fgetting-value-from-a-chained-promises%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









    0














    So as mentioned above I think your issue is based on not returning the results of your document search so both examples below handle that.



    I also noticed that you were using async tags on your functions but not ever using await so I wanted to give examples of both ways of doing it in case you wanted to use Async/Await but weren't certain how.



    In the promise chain example I'm relying on the syntax of arrow functions to create the returns (no {} means return right side of equation) since none of your given code requires data manipulation before return (if your actual code needs that you should of course use brackets and remember your return statement :D )



    If you choose to use Async/Await you can structure the code much more closely to synchronous examples and use try catch statements. Sometimes I find this syntax more clear if I have to do a lot of processing/manipulation before returning a result.



    Good Luck :)!






    // Promise Chains
    const addService = (req, res) =>
    checkCategoryExists(param)
    .then(result => /* do stuff */)
    .catch(err => console.error(err.message));

    const checkCategoryExists = param =>
    db.collection(collectionName.doc(param)
    .get()
    .then(categoryDoc =>
    Promise.resolve((categoryDoc.exists && categoryDoc.data().param === param))
    );

    // OR using Async/Await
    const addService async (req, res) => {
    try {
    const catExists = await checkCategoryExists(param);
    if (!catExists) {
    throw new Error('error code');
    }

    // Do Stuff.
    } catch (error) {
    console.error(error);
    }
    };

    const checkCategoryExists = async param => {
    try {
    const docs = await db.collection(collectionName)
    .doc(param)
    .get();

    return (docs.exists && docs.data().param === param);
    } catch (error) {
    console.error(error)
    }
    }








    share|improve this answer






























      0














      So as mentioned above I think your issue is based on not returning the results of your document search so both examples below handle that.



      I also noticed that you were using async tags on your functions but not ever using await so I wanted to give examples of both ways of doing it in case you wanted to use Async/Await but weren't certain how.



      In the promise chain example I'm relying on the syntax of arrow functions to create the returns (no {} means return right side of equation) since none of your given code requires data manipulation before return (if your actual code needs that you should of course use brackets and remember your return statement :D )



      If you choose to use Async/Await you can structure the code much more closely to synchronous examples and use try catch statements. Sometimes I find this syntax more clear if I have to do a lot of processing/manipulation before returning a result.



      Good Luck :)!






      // Promise Chains
      const addService = (req, res) =>
      checkCategoryExists(param)
      .then(result => /* do stuff */)
      .catch(err => console.error(err.message));

      const checkCategoryExists = param =>
      db.collection(collectionName.doc(param)
      .get()
      .then(categoryDoc =>
      Promise.resolve((categoryDoc.exists && categoryDoc.data().param === param))
      );

      // OR using Async/Await
      const addService async (req, res) => {
      try {
      const catExists = await checkCategoryExists(param);
      if (!catExists) {
      throw new Error('error code');
      }

      // Do Stuff.
      } catch (error) {
      console.error(error);
      }
      };

      const checkCategoryExists = async param => {
      try {
      const docs = await db.collection(collectionName)
      .doc(param)
      .get();

      return (docs.exists && docs.data().param === param);
      } catch (error) {
      console.error(error)
      }
      }








      share|improve this answer




























        0












        0








        0







        So as mentioned above I think your issue is based on not returning the results of your document search so both examples below handle that.



        I also noticed that you were using async tags on your functions but not ever using await so I wanted to give examples of both ways of doing it in case you wanted to use Async/Await but weren't certain how.



        In the promise chain example I'm relying on the syntax of arrow functions to create the returns (no {} means return right side of equation) since none of your given code requires data manipulation before return (if your actual code needs that you should of course use brackets and remember your return statement :D )



        If you choose to use Async/Await you can structure the code much more closely to synchronous examples and use try catch statements. Sometimes I find this syntax more clear if I have to do a lot of processing/manipulation before returning a result.



        Good Luck :)!






        // Promise Chains
        const addService = (req, res) =>
        checkCategoryExists(param)
        .then(result => /* do stuff */)
        .catch(err => console.error(err.message));

        const checkCategoryExists = param =>
        db.collection(collectionName.doc(param)
        .get()
        .then(categoryDoc =>
        Promise.resolve((categoryDoc.exists && categoryDoc.data().param === param))
        );

        // OR using Async/Await
        const addService async (req, res) => {
        try {
        const catExists = await checkCategoryExists(param);
        if (!catExists) {
        throw new Error('error code');
        }

        // Do Stuff.
        } catch (error) {
        console.error(error);
        }
        };

        const checkCategoryExists = async param => {
        try {
        const docs = await db.collection(collectionName)
        .doc(param)
        .get();

        return (docs.exists && docs.data().param === param);
        } catch (error) {
        console.error(error)
        }
        }








        share|improve this answer















        So as mentioned above I think your issue is based on not returning the results of your document search so both examples below handle that.



        I also noticed that you were using async tags on your functions but not ever using await so I wanted to give examples of both ways of doing it in case you wanted to use Async/Await but weren't certain how.



        In the promise chain example I'm relying on the syntax of arrow functions to create the returns (no {} means return right side of equation) since none of your given code requires data manipulation before return (if your actual code needs that you should of course use brackets and remember your return statement :D )



        If you choose to use Async/Await you can structure the code much more closely to synchronous examples and use try catch statements. Sometimes I find this syntax more clear if I have to do a lot of processing/manipulation before returning a result.



        Good Luck :)!






        // Promise Chains
        const addService = (req, res) =>
        checkCategoryExists(param)
        .then(result => /* do stuff */)
        .catch(err => console.error(err.message));

        const checkCategoryExists = param =>
        db.collection(collectionName.doc(param)
        .get()
        .then(categoryDoc =>
        Promise.resolve((categoryDoc.exists && categoryDoc.data().param === param))
        );

        // OR using Async/Await
        const addService async (req, res) => {
        try {
        const catExists = await checkCategoryExists(param);
        if (!catExists) {
        throw new Error('error code');
        }

        // Do Stuff.
        } catch (error) {
        console.error(error);
        }
        };

        const checkCategoryExists = async param => {
        try {
        const docs = await db.collection(collectionName)
        .doc(param)
        .get();

        return (docs.exists && docs.data().param === param);
        } catch (error) {
        console.error(error)
        }
        }








        // Promise Chains
        const addService = (req, res) =>
        checkCategoryExists(param)
        .then(result => /* do stuff */)
        .catch(err => console.error(err.message));

        const checkCategoryExists = param =>
        db.collection(collectionName.doc(param)
        .get()
        .then(categoryDoc =>
        Promise.resolve((categoryDoc.exists && categoryDoc.data().param === param))
        );

        // OR using Async/Await
        const addService async (req, res) => {
        try {
        const catExists = await checkCategoryExists(param);
        if (!catExists) {
        throw new Error('error code');
        }

        // Do Stuff.
        } catch (error) {
        console.error(error);
        }
        };

        const checkCategoryExists = async param => {
        try {
        const docs = await db.collection(collectionName)
        .doc(param)
        .get();

        return (docs.exists && docs.data().param === param);
        } catch (error) {
        console.error(error)
        }
        }





        // Promise Chains
        const addService = (req, res) =>
        checkCategoryExists(param)
        .then(result => /* do stuff */)
        .catch(err => console.error(err.message));

        const checkCategoryExists = param =>
        db.collection(collectionName.doc(param)
        .get()
        .then(categoryDoc =>
        Promise.resolve((categoryDoc.exists && categoryDoc.data().param === param))
        );

        // OR using Async/Await
        const addService async (req, res) => {
        try {
        const catExists = await checkCategoryExists(param);
        if (!catExists) {
        throw new Error('error code');
        }

        // Do Stuff.
        } catch (error) {
        console.error(error);
        }
        };

        const checkCategoryExists = async param => {
        try {
        const docs = await db.collection(collectionName)
        .doc(param)
        .get();

        return (docs.exists && docs.data().param === param);
        } catch (error) {
        console.error(error)
        }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 23 '18 at 21:07

























        answered Nov 23 '18 at 21:00









        D LowtherD Lowther

        1,3481415




        1,3481415
































            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.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452778%2fgetting-value-from-a-chained-promises%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

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            RAC Tourist Trophy