#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2016
    Posts
    5
    Rep Power
    0

    Exclamation Promises and Fetch API problem


    I'm trying hard to get this api to work but somehow I am missing something. The idea is to provide one fetch api library for the whole site, so that I don't need to rewrite or copy the same few lines of code all over the place but I am having problems at the final stage, returning data. I only end up with a pending Promise, despite using async functions.

    The API is called here:
    Code:
    import APIFetch from '../lib/Fetch';
    var f = APIFetch().get("/stats/all_categories")
    console.log(f)
    And this is the API itself:
    Code:
    const APIPath = "http://localhost:4000"
    
    var APIHeaders = {
        "Accept": "appilication/json; charset=utf-8",
        "Content-Type": "application/json"
    }
    
    
    
    class APICall {
        constructor(path, headers) {
            this.path = path
            this.headers = headers
    
            this.request = new Request(path, headers: headers)
        }
    
        async _fetch(r) {
            return await fetch(r).then(function(res) {
                if(res.ok == false) {
                    throw new Error(res.status + " " + res.statusText)
                }
    
                return res.json()
            }).then(function(data) {
                return data
            }).catch(function(err) {
                console.error(err.message)
            })
        }
    
        _genPath(path) {
            return this.path + path
        }
    
        async get(path, r) {
            const value = await this._fetch(new Request(this._genPath(path), {
                method: "GET",
                headers: this.headers
            }))
    
            console.log(value)
            return value
        }
    
        post(path, body = {}) {
            return this._fetch(new Request(this._genPath(path), {
                method: "POST",
                body: JSON.stringify(body),
                headers: this.headers
            })
        )}
    }
    
    export default function APIFetch(path = APIPath) {
        return new APICall(path, new Headers(APIHeaders))
    }
    The console.log() in the get() method works fine. But the console.log(f) in the end only shows a still pending Promise, although I would expect that to be the final data, retrieved through the API. Can anyone spot what am I doing wrong?
  2. #2
  3. Wiser? Not exactly.
    Devshed God 2nd Plane (6000 - 6499 posts)

    Join Date
    May 2001
    Location
    Bonita Springs, FL
    Posts
    6,031
    Rep Power
    4101
    I'm not familiar with that type of code, but some googling of the async/await keywords suggests that you need to use await when calling the get function.

    Code:
    var f = await APIFetch().get("/stats/all_categories")
    Recycle your old CD's



    If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2015
    Posts
    70
    Rep Power
    3
    Why don't you simply use some Promise based client such as Axios ?
    https://github.com/mzabriskie/axios

IMN logo majestic logo threadwatch logo seochat tools logo