Running Functions Out of Order in JavaScript - An exploration of Asynchronous Execution

I've been working on understanding how to manage the execution order of my script using asynchronous functions and promises. Despite going through numerous resources, I'm still struggling with getting it to work as expected:

My approach involves having a Vue.js object that contains methods, and triggering a series of async functions when the app is mounted:

var testAPP = new Vue({
    el: '#test-app',
    data: {

    },
    // Methods code here...
})

The anticipated output sequence should be like this:

User story goes here.
Expected console log output.
More user stories...

However, the actual result doesn't match the expected order, showing immediate logs instead of the delays between steps.

Despite trying different methods, including adjusting promise returns and function dependencies, the issue persists.

Why are my functions not honoring the specified order within the async process?

Any insights or suggestions would be greatly appreciated!

Here's the simple HTML setup used for testing in Edge:

<!DOCTYPE html>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script type="text/javascript" src="path/to/your/script.js"></script>

Answer №1

Your code utilizes `await` without the necessary `async` keyword

first_step: async function() {  // <-- remember to use async keyword
  console.log('Interacting with my dog!')
  return this.fake_fetch() // <-- make sure to include a return statement
    .then((data) => {
      let compliment = "Buddy is a " + data
      console.log(compliment)
      return ("nap.")
    })
    .then((data) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log("Taking a break with " + data);
          resolve(true)
        }, 20000)
      })
    })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I attempted to publish my React application using gh-pages and encountered the following error: "The argument for 'file' must be a string. However, it was received as undefined."

I encountered an issue while attempting to deploy my React application with gh-pages. The error message I'm facing states: "The 'file' argument must be of type string. Received type undefined." Initially, I suspected that the problem was wi ...

Do you have to host a node server to run Angular applications?

(say) I am currently working on a project that utilizes Laravel or PHP for the back-end and Angular for the front-end. In my setup, I am using angular.js files from a CDN, which should work fine. However, I find myself confused when tutorials and books me ...

Corrected typing mistakes using vuex

Currently, I am working on a project using Vue 3 and TypeScript. One issue I am facing is related to vuex. I have created a file named vuex.d.ts to access $store inside Components: import { Store } from 'vuex'; import { State } from '@/stor ...

Guide on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. https://i.sstatic.net/kRJOb.png Here is my HTML code: <section class="favorit ...

What is the best way to align a badge icon regardless of the avatar's size?

I'm working on creating an avatar component with badges. However, I'm facing an issue with the positioning of the badges relative to the avatar size. The image below provides a clear illustration of the problem. Can you guide me on adjusting the ...

Selenium automating the process of clicking a button without a defined name or id

I have been encountering difficulties while trying to automate this particular page. Once I log in, I reach a page where I am required to click on a button before being redirected to the next page. The issue lies in the fact that this button lacks a name o ...

JavaScript: Creating a Function that Returns an Object with an Undefined `this.variable`

While using javascript, I encountered an issue with instance variables. Declaring a variable as "this.variable" works fine until my function returns an object. However, if the function returns a String or Number, there are no issues. But when it returns ...

Steps to invoke a function to add an element into a list

Every time a user clicks on a button, I want to generate a new tab. In this tab, when the user clicks again, I want a function to be called like: onclick('+reportname+','+report type+') onclick("'+reportname+'","'+repor ...

What could be causing my THREE.js Documentation Box to malfunction?

I am a newcomer trying to get the hang of THREE.js. I delved into the THREE.js Documentation and attempted to implement the code, but when I loaded my HTML page, it appeared blank. I am at a loss for what to do next. I utilized Visual Studio Code for codin ...

The display of 'App' seems to be experiencing issues within the render method

Can someone help me with this issue? I am encountering the following error: Uncaught Error: Invariant Violation: Element type is invalid - expected a string for built-in components or a class/function for composite components, but received an object. Bel ...

When utilizing TypeScript with Nuxt3, the error message "Module '#imports' or its corresponding type declarations could not be found" may be encountered

I have extensively searched for a solution to this issue, but unfortunately, I have not been able to find any results. When working with a very basic component, I encounter the following error: Cannot find module '#imports' or its corresponding ...

Breadcrumb navigation that is determined by data hierarchies and relationships between parent and child items

I am looking to implement a dynamic breadcrumb system on my website using data-driven methodology. The necessary data is stored in a MariaDB database and has the following structure: parent_id | parent_name | child_id | child_name ——————— ...

Issue with Vuex getters not properly returning data

I am encountering an issue with a Vuex getter that is supposed to return the state of courseData. Despite the getter being present and having values when I check it using console.log(this.$store.getters), I am unable to access the data. When I try to use c ...

Executing a child component function once the parent component data is loaded in Angular 5

In my project, I have a parent component called program-page.component where I am invoking a function to fetch some data. ngOnInit() { this.getProgress(); } getFirstProgramItem() { this._contentfulService.getProgramItem(4, 1) .then((programItem) = ...

Issues with AngularJS Validation not functioning properly with File Inputs marked as 'Required'

I've been experimenting with this issue and haven't been able to solve it. While creating an Angular form, I found that validation works fine when the required attribute is used in a text field. However, when I tried adding a file input type with ...

Disabling vertical scrollbar in textarea within Bootstrap modal using CSS, jQuery, and C# in .NET MVC framework

I am passing data to the Bootstrap modal using jQuery from my database. The form values can change from a single row to multiple rows. I do not want a scrollbar, but instead I want the textarea element to automatically adjust its height to fit the content. ...

Attention: Vanishing within specified time limit

Can you help me find a technology that will display a warning message and make it disappear with a nice effect over a set amount of time? I think AJAX or JavaScript might be able to achieve this. The warning message I'm currently using is: <scrip ...

Using double parentheses in JavaScript

Although I am not a JS/Front-end developer, I currently need to dive into one of React.JS UI libraries. During my exploration, I stumbled upon something that seems unusual to me. return /*#__PURE__*/(0, _jsxRuntime.jsxs)(TextFieldRoot, (0, _extends2.defaul ...

The interaction between jQuery and Rails through ajax calls

Attempting to work with basic functionality, Sending a request with data and receiving a response with data, then displaying it using jQuery and Rails This piece of code pertains to the frontend. $("#internal_btn").click(function() { //windo ...

In Cytoscape.js, Chrome is having trouble selecting nodes

When using cytoscape.js, I have a network where selecting a node should change the color of the inner circle from green to black. In Mozilla Browser, this works fine: However, when attempting the same network in Google Chrome, the selection doesn't w ...