Using promise with GraphRequestManager
Asked Answered
M

1

6

Does anyone have an example on how to use promise with GraphRequestManager? I get Cannot read property then of undefined error in my action creator.

function graphRequest(path, params, token=undefined, version=undefined, method='GET') {
return new Promise((resolve, reject) => {
    new GraphRequestManager().addRequest(new GraphRequest(
        path,
        {
            httpMethod: method,
            version: version,
            accessToken: token
        },
        (error, result) => {
            if (error) {
                console.log('Error fetching data: ' + error);
                reject('error making request. ' + error);
            } else {
                console.log('Success fetching data: ');
                console.log(result);
                resolve(result);
            }
        },
    )).start();
});

}

I call the above using my action creator

export function accounts() {
return dispatch => {
    console.log("fetching accounts!!!!!!");
    dispatch(accountsFetch());
    fbAPI.accounts().then((accounts) => {
        dispatch(accountsFetchSuccess(accounts));
    }).catch((error) => {
        dispatch(accountsFetchFailure(error));
    })
}

}

I get 'Success fetching data:' in the console along with the result before the error. So the API call is made successfully. The error is after fetching the accounts in fbAPI.accounts().then((accounts) which I think is due to GraphRequestManager returning immediately instead of waiting.

Mayamayakovski answered 25/9, 2016 at 22:58 Comment(0)
L
3

I have a solution for you. My provider look like this :

 FBGraphRequest = async (fields) => {
        const accessData = await AccessToken.getCurrentAccessToken();
        // Create a graph request asking for user information
        return new Promise((resolve, reject) => {
            const infoRequest = new GraphRequest('/me', {
                    accessToken: accessData.accessToken,
                    parameters: {
                        fields: {
                            string: fields
                        }
                    }
                },
                (error, result) => {
                    if (error) {
                        console.log('Error fetching data: ' + error.toString());
                        reject(error);
                    } else {
                        resolve(result);
                    }
                });

            new GraphRequestManager().addRequest(infoRequest).start();
        });
    };



  triggerGraphRequest = async () => {
            let result = await this.FBGraphRequest('id, email');
            return result;
  }

That works great ! I let you adapt my solution to your system.

Larson answered 30/8, 2018 at 15:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.