簡體   English   中英

如何在非異步 function 中調用異步 function

[英]How to call an Async function in Non-Async function

我是 React Js 的新手,並嘗試使用fetch進行 API 調用。

我已經編寫了一個通用異步 function 用於 API 調用,以將請求發送到 API 端點。 function 在另一個類的 function 中被調用,它應該解析結果並將值返回給父 function 調用。

這是我的實用程序 class 和調用端點的 function:

export default class RestUtil {
  getModel = async (model) => {
    let url = 'http://api.xyz.com/' + model;
    const apiCall = await fetch(url,
        {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': 'Bearer xyz'
            }
        });
    return  apiCall.json();
 }
}

以下是導致問題的我的 React 組件:

export default class MyComponent extends React.Component {
   componentDidMount() {
     this.populateUsersDropDown();
   }

   populateUsersDropDown() {
     let users = this.fetchUsers();
     // Here the `users` is undefined. <-------- Issue

     //Do some other work with users

     /*Populate users in 
                 the dropdown*/
   }

   fetchUsers() {
     new RestUtil()
         .getModel('users')
         .then(data => {
             /* Do some other work with data */
             return data;
         })
   }

}

現在我希望 populateUsersDropDown() 等待 fetchUsers() 完成它then部分並返回數據並繼續。 但我在用戶變量中收到undefined 在哪里,在我的then部分中,我可以看到數據。

需要一些幫助來解決這個問題嗎?

您的fetchUsers方法不返回任何內容。

    async fetchUsers() {
     const users = await new RestUtil().getModel('users');

     return users;
   }

這應該工作

暫無
暫無

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

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