繁体   English   中英

异步 Function 运行故障 - Javascript

[英]Asynchronous Function running out of order - Javascript

我正在尝试准确了解如何使用异步函数和承诺来监督我的脚本运行的顺序。 在这一点上,我已经阅读/观看了许多信息资源以尝试正确解决此问题,但是关于我的代码的某些内容不起作用:

我有一个通用的 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()
    }
})

根据我“认为”正确的顺序,我期望得到的结果是:

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.

忽略 output 语句的愚蠢,这就是它们应该出现的顺序。 我当前的代码给了我这个:

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.

前四行立即出现,感觉不对,因为我的内置延迟应该在下一个触发之前停止每个“步骤”function。

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

为什么我的函数同时开始,而不是按照我在异步 function 中内置的“顺序”?

感谢您的任何帮助!

此外,我用来在 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>

您正在使用等待,但没有异步

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