简体   繁体   English

异步 Function 运行故障 - Javascript

[英]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:我有一个通用的 vue.js object 包含我的方法,并在安装应用程序时异步运行一系列函数:

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.忽略 output 语句的愚蠢,这就是它们应该出现的顺序。 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.前四行立即出现,感觉不对,因为我的内置延迟应该在下一个触发之前停止每个“步骤”function。

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.我已经尝试了很多方法,在方法中将“my_day()”设为自己的 function 并通过this.my_day()调用它,但这并没有什么不同。 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.我已经尝试在 promise 上使用不同的 return 语句,以及使每个后续步骤 function 依赖于其前身的变量,但这些导致相同的功能。

Why are my functions starting at the same time and not following the 'order' I have built into my async function?为什么我的函数同时开始,而不是按照我在异步 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:此外,我用来在 Edge 中运行的 html 也很简单,我只是对控制台感兴趣:

<!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)
      })
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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