即使使用async / await方法也有待处理的承诺

时间:2019-12-09 12:25:36

标签: typescript promise async-await

我有一个服务类,该类具有一种从api提取数据的方法:



def home():
    homepage = Tk()
    btn = Entry(homepage)
    btn.grid(row=1, column=1)
    ent = Button(homepage, text='DESTROY')
    crts = Button(homepage, text='CREATE')
    ent.grid(row=3, column=3)
    crts.grid(row=3, column=4)

    def dlt(event): >Here the Entry widget is destroyed
        # global btn
        btn.grid_remove()

    def crt(event): >Here the Entry widget is created but only ones
        global btn
        btn = Entry(homepage)
        btn.grid(row=1, column=1)
        homepage.

    ent.bind("<Button-1>", dlt)
    crts.bind("<Button-1>", crt)


    homepage.mainloop()


home()

此类方法从另一个文件使用,如下所示:

class TenderTableService{
    fetchOngoingTenders =  async ()   =>  {
        const response = await fetch('http://127.0.0.1:5000/api/tender/');
        let tenderList: Array<Tender> = (JSON).parse(await response.json());
        return tenderList;
    };
}

export default TenderTableService;

我不知道如何防止变量形式返回挂起状态

1 个答案:

答案 0 :(得分:1)

那是因为tenderTableService.fetchOngoingTenders();返回了一个promise,因为它实际上是一个异步函数。如果要访问bidList,可以通过链接.then()来完成,即:

const tenderTableService : TenderTableService = new TenderTableService();
tenderTableService.fetchOngoingTenders().then((tenderList) => {
    // Do something with tenderList here
});

...这意味着所有处理tenderList值的逻辑都需要包装在.then()回调中。如果上面的代码也包装在一个函数中,则可以将其转换为异步函数并使用await:

async function yourFunction() {
    const tenderTableService : TenderTableService = new TenderTableService();
    const tenderList = await tenderTableService.fetchOngoingTenders();

    // Do something with tenderList here
}