简体   繁体   中英

javascript code not proceeding after await

I am trying to use cookie-toss library on my NuxtJS to try and share authentication with tokens between different domains. The problem is when I try their example to get the localstorage in sattelite2.com.. The code does not proceed in console.log(result) as shown below

  async mounted() {
    console.log("went in");
    const result = await get({
      iframeUrl: "http://satellite2.com:3000/ckjtt/",
      dataKey: "chocolate-chip-oatmeal"
    });
    // const result = localStorage['ckj-user']
    console.dir(`result: ${JSON.stringify(result)}`);
  },

I am a part time frontend developer who has relied on frameworks, so the basic of async/await is something that I have not fully understand. I can not understand why it does not proceed based on his repo

You should wrap your await get(...) call in an async IIFE or a plain async function. The await keyword can be only used in an async function. Top level await will be introduced in the future: https://v8.dev/features/top-level-await#:~:text=Top%2Dlevel%20await%20enables%20developers,they%20start%20evaluating%20their%20body .

It is also a good practice to introduce error handling in your code. With await try - catch is a common practice.

import { get } from "cookie-toss";

async function fetchData() {
  let result;
  try {
    result = await get({
      iframeUrl: 'https://hub.com/cookie-toss.html',
      dataKey: 'chocolate-chip-oatmeal',
    });
    console.log(result);
  } catch(error) {
      console.error(`Unable to fetch data. Error: ${error.message || 'Unexpected error'}`);
      // error handling
   }
}

fetchData();

mounted is already predefined as a regular function. so adding async wont do anything. you have to declare your method first before calling in your created or mounted

    export default {
        data() {
            return {
                results: null
            }
        },
        mounted() {
            this.getDataFromApi()
        },
        methods: {
            async getDataFromApi() {
                this.results = await get({
                  iframeUrl: "http://satellite2.com:3000/ckjtt/",
                  dataKey: "chocolate-chip-oatmeal"
                })
            }
        }
    }

since you're using nuxtJS you can just use the async fetch already provided

export default {
    data() {
      return {
        results: null
      }
    },
    activated() {
      // Call fetch again if last fetch more than 30 sec ago
      if (this.$fetchState.timestamp <= Date.now() - 30000) {
        this.$fetch()
      }
    },
    async fetch() {
      this.results= await get({
              iframeUrl: "http://satellite2.com:3000/ckjtt/",
              dataKey: "chocolate-chip-oatmeal"
      })
    }
  }

or asyncData (I would recommend this)

import { get } from "cookie-toss";

export default {
    async asyncData({ params, $http }) {
      const results = await get({
              iframeUrl: "http://satellite2.com:3000/ckjtt/",
              dataKey: "chocolate-chip-oatmeal"
      })
      return { results}
    }
  }

then you can access it in your component with this.results or results on your template.

you can read more about it here https://nuxtjs.org/docs/2.x/features/data-fetching/

additionally you can create a plugin to for your get from cookie-toss

create a file called cookie-toss.js in your plugins folder and add this code to it

import { get } from 'cookie-toss';

export default ({ app }, inject) => {
    inject('get', get);
}

and then in your plugins array in your nuxt.config.js add the path to your plugin

 plugins: [
    '@/plugins/cookie-toss.js'
  ],

now you can access your get in the app context.

export default {
  async asyncData({app, $get}) {
    // app.$get or $get
    const result = await $get({
      iframeUrl: "http://satellite2.com:3000/ckjtt/",
      dataKey: "chocolate-chip-oatmeal",
    });
    return { result };
  },
};

if you get the error of window is not defined add mode: 'spa' to your nuxt.config.js or ssr: false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM