简体   繁体   中英

Asynchronous Function running out of order - Javascript

I'm trying to learn exactly how to oversee the order in which my script runs using asynchronous functions and promises. At this point I've read/watched many information resources to try to get this right but something about my code just isn't working:

I have a generic vue.js object containing my methods, and running the series of functions asynchronously when the app is mounted:

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

    },
    methods: {
        fake_fetch: function () {
            return new Promise((resolve) => { 
                setTimeout(() => {console.log("Returning fetch results."); resolve("good boy!")}, 10000) 
            })
        },
        first_step: function () {
            console.log('Playing with my puppy!')
            this.fake_fetch()
            .then((data) => {
                let praise = "Buddy is a " + data
                console.log(praise)
                return ("nap.")
            })
            .then((data) => {
                return new Promise((resolve) => {
                    setTimeout(() => {console.log("Phew! We are taking a " + data); resolve(true)}, 20000)
                })
            })
        },
        second_step: function () {
            console.log('Baking some cookies!')
            this.fake_fetch()
            .then((data) => {
                data = data.replace(" ", ", ")
                let praise = "Oh man these are " + data
                console.log(praise)
                return ("nap.")
            })
            .then((data) => {
                return new Promise((resolve) => {
                    setTimeout(() => {console.log("I'm so full, I'm taking a " + data); resolve(true)}, 20000)
                })
            })
        },
        third_step: function () {
            console.log('Putting out a hit on Polly')
            this.fake_fetch()
            .then((data) => {
                let praise = "The job was a success? You did " + data
                console.log(praise)
                return ("nap.")
            })
            .then((data) => {
                return new Promise((resolve) => {
                    setTimeout(() => {console.log("A moment of silence for Polly as he takes a dirt " + data); resolve(true)}, 20000)
                })
            })
        },
        get_started: function () {
            v = this
            async function my_day(v) {
                const task_one = await v.first_step()
                const task_two = await v.second_step()
                const task_three = await v.third_step()
                return ([task_one, task_two, task_three])
            }
            my_day(v).then((data) => {
                if (false in data) {
                    return ("Something went wrong.")
                } else {
                    return ("My day is done, time to rest... again.")
                }
            })
        },
    },
    mounted: function () {
        this.get_started()
    }
})

The result I expect to get based on the order I 'thought' would be correct is this:

Playing with my puppy!
Returning fetch results.
Buddy is a good boy!
Phew! We are taking a nap.
Baking some cookies!
Returning fetch results.
Oh man these are good, boy!
I'm so full, I'm taking a nap.
Putting out a hit on Polly
Returning fetch results.
The job was a success? You did good boy!
A moment of silence for Polly as he takes a dirt nap.
My day is done, time to rest... again.

Ignoring the silliness of the output statements, thats the order they should appear. My current code gives me this:

Playing with my puppy!
Baking some cookies!
Putting out a hit on Polly
My day is done, time to rest... again.
Returning fetch results.
Buddy is a good boy!
Returning fetch results.
Oh man these are good, boy!
Returning fetch results.
The job was a success? You did good boy!
Phew! We are taking a nap.
I'm so full, I'm taking a nap.
A moment of silence for Polly as he takes a dirt nap.

The first four lines come up right away which doesn't feel right as there should be my built in delays stalling each 'step' function before the next one fires.

I've tried many things from making 'my_day()' its own function within methods and calling it via this.my_day() but that didn't make a difference. I've tried playing around with different return statements on the promises as well as making each following step function dependent on the variable of its predecessor but these resulted in the same functionality.

Why are my functions starting at the same time and not following the 'order' I have built into my async function?

Thank you for any help!

Also the html I used to run this in Edge is simple, I was just interested in the console:

<!DOCTYPE html>
<script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
<script type="text/javascript" src="C:\Users\adarwoo\Documents\Python Scripts\JS\async2.js"></script>

You are using await, but there is no async

first_step: async function() {  // <-- async needed
  console.log('Playing with my puppy!')
  return this.fake_fetch() // <-- return needed
    .then((data) => {
      let praise = "Buddy is a " + data
      console.log(praise)
      return ("nap.")
    })
    .then((data) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log("Phew! We are taking a " + data);
          resolve(true)
        }, 20000)
      })
    })
}

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