簡體   English   中英

如何在 javascript 類中的另一個函數中調用異步函數?

[英]How can i call an async function inside another function in a javascript class?

我正在嘗試在類中調用異步函數,但不斷收到錯誤,提示this.getcategory.then is not a function at category.js:21我有一個表單,管理員使用該表單將更多類別添加到數據庫中。 categform.addEventListener('submit', e => {此行將偵聽提交事件,然后使用以下代碼片段獲取數據並將其插入到數據庫中

super.postText("../includes/getcategoy.inc.php", categformData)
            .then(res => {
                console.log(res);
                // 1. if the results are ok fetch the fresh data from the database
                this.getcategory.then(
                    res => {
                        console.log(res);
                    }
                )
            }).catch((error) => {
                console.error('Error:', error);
            });

現在上面的代碼返回一個承諾,然后如果結果正常,我調用同一個類中的另一個函數從數據庫中獲取最新數據。 功能是this.getcategory記住我在then內部調用函數並且出現錯誤。 我在then內部調用的原因是因為只希望在將數據發送到數據庫后才執行它已解決。
但是當我在第一個函數之外調用它時,我沒有收到錯誤..如果您只查看catch 塊,我已將其注釋掉。 如果我在那里調用它,我不會收到錯誤消息。 但我不想在那里打電話。 記住該函數返回一個promise,它被定義為類中的最后一個函數

我該如何解決這個問題,下面是整個代碼

import { FETCH } from "./fetch.js";

class CATEGORY extends FETCH {
    constructor() {
        super()
    }

listencategory() {
    //1. Listen for the button click
    const categform = document.getElementById('categotyform');
    categform.addEventListener('submit', e => {
        e.preventDefault();
        //2. get the data from form
        const categformData = new FormData(categform);
        super.postText("../includes/getcategoy.inc.php", categformData)
            .then(res => {
                // console.log(res);
                // 1. if the results are ok fetch the fresh data from the database
                this.getcategory.then(
                    res => {
                        console.log(res);
                    }
                )
            }).catch((error) => {
                console.error('Error:', error);
            });
    });
    //this.getcategory().then(res=>{
    //    console.log(res);
    //    
    //})

}

async getcategory() {
    try {
        const results = await super.get("../includes/getcategoy.inc.php");
        return results;
    } catch (error) {
        console.log(error);
    }
}
}

const categ = new CATEGORY;
categ.listencategory();

我正在嘗試獲取async getcategory()返回的數據

getcategory 是一個Async函數,應該像下面這樣進行函數調用。

this.getcategory().then(
                        res => {
                            console.log(res);
                        }
                    )

此鏈接可幫助您有效地創建和使用承諾。 異步函數 - 使承諾友好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM