简体   繁体   中英

Javascript how to properly await for a function before triggering the next one?

I'm having a issue with await and async functions where a function that should await for the completion of a fetch command triggers before it's done, hence i'm getting undefined value errors.

here is the function executing fetch:

async function BoardGet() {

        let conjunction = "Bearer " + responseToken.response.token 

        var myHeaders = new Headers()
        myHeaders.append("Authorization", conjunction)
        myHeaders.append("Content-Type", "application/json")

        var raw = JSON.stringify({})

        var requestOptions = {
            method: 'GET',
            headers: myHeaders,
            //body: raw,
            redirect: 'follow'
        }

        fetch("https://link-to-my-database", requestOptions)
            .then(response => response.text())
            .then(function(result) {
                let tempAvailableBoards = result
                availableBoards = JSON.parse(tempAvailableBoards)
                console.log("available boards: ", availableBoards)
            })
            .catch(error => console.log('error', error))

just fetches a JSON file which gets parsed into a variable. The problem is when I call my 2nd function which uses availableBoards and even though I used await, which from my understanding should force the next codeblock to wait, doesn't

async function BoardCheck() {

        await BoardGet()

        //check for board before creating a new one, if board already created return
        for(i = 0; i < availableBoards.response.data.length; i++) {
            if(boardId == availableBoards.response.data[i].fieldData._id_Miro_MiroBOARD) {
                console.log("This board is already in the database, now exiting this board create....")
                recordId = availableBoards.response.data[i].recordId // denotes filemaker data id for easier access (1 less loop)
                return
            }
            else if(i == availableBoards.response.data.length) {
                console.log("Borad not found, creating it...")
                BoardCreate()
            }
        }
    }

I get this error: Uncaught (in promise) TypeError: Cannot read property 'response' of undefined at BoardCheck After the Error I get response from BoardGet, judging by that await doesn't make the code actually await

Am I using await in a wrong way?

You don't return a Promise that you can await from your BoardGet function. Write return before your fetch() call inside the function:

async function BoardGet() {

   // ...

   // return the promise
   return fetch("https://link-to-my-database", requestOptions)
            .then(response => response.text())
            .then(function(result) {
                let tempAvailableBoards = result
                availableBoards = JSON.parse(tempAvailableBoards)
                console.log("available boards: ", availableBoards)
            })
            .catch(error => console.log('error', error))
}

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