Calling promises inside of object in ES6 [duplicate]

49
May 01, 2018, at 02:40 AM

This question already has an answer here:

  • What is the value of “this” inside an arrow function that is defined inside a class [duplicate] 2 answers
  • Methods in ES6 objects: using arrow functions 3 answers
  • Arrow Functions and This [duplicate] 5 answers
  • Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? 2 answers

I created an object with nested functions, the goal is to be able to call a new promise from each function that is called with a different HTTP method and body, I am defining a function called apiCall, its job its to be called by the other functions and return a promise.

When I import api from another file and use api.apiCall( method, url, body ) it does execute and returns a promise. However when I try something like api.get(url), it returns an error 'Cannot read then of undefined' which tells me a promise is not being returned, I don't understand why this is happening since I am calling apiCall with this and returning in it inside of the function.

Is there a reason why this.apiCall() is not working? I saw other posts with similar questions like mine and all of them say that you can call a function using this to reference a key inside of the object. Thank you for your help

export const api = {
    apiCall: async ( method, url, body ) => {
            const options = {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify( body )
            };
            try {
                const response = await fetch( url, options );
                return response.json();
            }
            catch ( e ) {
                throw e;
            }
        },
    get: ( url ) => {
        return this.apiCall( 'GET', url );
    },
    post: ( url, body ) => {
        return this.apiCall( 'POST', url, body );
    },
    put: ( url, body ) => {
        return this.apiCall( 'PUT', url, body );
    },
    getBaseURL: ( which ) => {
        return process.env.REACT_APP_BASE_URL ? `${ process.env.REACT_APP_BASE_URL }${ which }` : `${ which }`;
    }
};
READ ALSO
How do you get value? [duplicate]

How do you get value? [duplicate]

This question already has an answer here:

92
How to add object into an array javascript

How to add object into an array javascript

I'm trying to add an object to the expense array using the addExpense method

102
use mixins as class names in stylus

use mixins as class names in stylus

I'm a beginner to stylus and am working on a project with vue to create a small component libraryI wanted to know if there was a way to use mixins as class names to achieve the following:

90
Resource not found when encoded url is passed

Resource not found when encoded url is passed

When I call following url from my ionic app, I get error:

116