0

I am trying to wrap Ajax into a Bluebird promise wrapper, but am receiving:

Error: Unhandled rejection (stack trace here...)

wrapper1.js

let fetch = require('./wrapper2');

function requestWeb(type, url, data) {
    return new Promise(function(resolve, reject) {
        url = config.serverUrl + url.trim();

        let options = {
            type: type,
            data: data ? JSON.stringify(data) : null,
            dataType: 'json',
            contentType: 'application/json',
            crossDomain: true,
            timeout: 15000,
            xhrFields: { withCredentials: true }
        };

        fetch(url, options)
            .then(data => {
                resolve(data);
            })
            .catch(err => {
                console.log('web api error: ' + err.message);
                notify('Please check your interet connection');
                reject(err);
            });
    });
}

wrapper2.js

import Promise from 'bluebird';

export default function(url, options) {
    return new Promise(function(resolve, reject) {
        $.ajax(url, options)
            .done((result) => {
                resolve(result);
            })
            .fail((xhr, err) => {
                let proxy = new Error();
                proxy.message = err || 'error is null';
                proxy.name = 'ajax error';

                reject(proxy);
            });
    });
}

Please note Bluebird requires different error object on reject().

wayofthefuture
  • 8,339
  • 7
  • 36
  • 53

1 Answers1

0

I figured it out, BlueBird wants to warn you that a reject() call has been fired but you are not catching it. So I was using...

requestWeb(type, url, data).then((result)=>{});

So to fix, do one of two things: add the .catch() to the end of the call, or remove the reject(err) from the promise.

wayofthefuture
  • 8,339
  • 7
  • 36
  • 53
  • No, don't remove `reject()`, that's just suppressing errors. – Bergi Sep 13 '16 at 21:04
  • I was console logging the error so we could see errors, sending error to admin as well, but user could not see error. Then in about 100 places in the app we don't need a .catch() block. – wayofthefuture Sep 13 '16 at 21:06