簡體   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