0

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/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript" src="C:\Users\adarwoo\Documents\Python Scripts\JS\async2.js"></script>
2
  • your first_step and others are not async and are not returning anything Commented Feb 12, 2021 at 15:42
  • Ah yes, in my mind the .then() function's return, as the final return of that series, would have returned it back to the parent function calling first_step(). But now I have fixed it by adding a return around each this.fake_fetch() within each step and that has fixed the problem. Commented Feb 12, 2021 at 15:46

1 Answer 1

1

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)
      })
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Making the step functions asynchronous is not necessary in my case. But the not returning of this.fake_fetch() was my problem. As I mentioned to another user in the comments above my mindset was that the last .then() function's return value would have kicked that back up to the parent function calling first_step, second_step, etc. But I see now that was an oversight on my part. I added the returns to each step function but did NOT make the asynchronous and the desired output is achieved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.