Search code examples
javascriptnode.jsvue.jses6-promise

Understand Vue and Return and Async Await


I am new to Javascript and Vue and I am having a hard time wrapping my head around return, async and await work together. I come from a Python background and JS syntax is quite different

So... some background to the problem....I'm building a Vue blog and creating multiple Vuex stores using module mode. I am also creating a function to retrieve data from Prismic.

./store/blog.js

import {MyFunctions} from "../plugins/myfunctions.js";

export const actions = {
    async retrievePosts() {
        console.log("HELLO")
        return MyFunctions.MyFunction("blog_post");
    }
}

./plugins/myfunctions.js

import Prismic from "prismic-javascript";
import PrismicDom from "prismic-dom" //importing the Dom
import PrismicConfig from "../prismic.config.js";

export const MyFunctions = {
    MyFunction: async function (doctype) {
        console.log("Before")
        const api = await Prismic.getApi(PrismicConfig.apiEndpoint)
        let blog_post = {}
        const results = await api.query(
            Prismic.Predicates.at("document.type", doctype),
            { lang: "en-us" } //This is a Prismic query option
        )
        console.log("After")
        result = results.results

        return result;
    }
};

Heres my question:

  1. In blog.js, if I remove the word "return" in front of MyFunctions.MyFunction("blog_post") , the await in myfunctions.js do not get activated. Why? I say this because without the return, "Before" is console logged but "After" is not and nothing is returned.

A further question for my enlightenment:

  1. Where does return MyFunctions.MyFunction("blog_post") return to? So the data is returned to retrievePosts() but it is part of a {} which is a javascript object I believe? So does it become like a property inside {}?

Solution

  • Ans 1:You are actually returning a function to the caller of retrievePosts() in async mode. By removing return, function will be executed but it don't make any effect to the caller of retrievePosts() function.

    Ans 2:The MyFunctions.MyFunction("blog_post") is returned to the caller of retrievePosts() function.