1

The following ajax call that I'm handinglind with a promise

function hit_db()
{
    return new Promise(function (resolve, reject)
    {
        $.ajax({
            url: target_url,
            type: "GET",
            async: true,
            crossDomain: true,
            success: function (data) { //<--Ultimately I want this snippet to return this data variable
                resolve(data);
            },
            error: function (err) {
                reject(error);
            }
        });
    });
}
return hit_db().then(data => {. // <--EDIT
   return data;
});

Whenever I try to return data I get obj Promise instead of the server response which is supposed to say Great! Success!

I thought that once the promised was fulfilled I could return data which is the server response.

Here i'm taking about how can I unwrap the Promise object from the async response that I'm getting

Then using the async/await syntax stills returns an obj Promise

function hit_db()
{
    return new Promise(function (resolve, reject)
    {
        $.ajax({
            url: target_url,
            type: "GET",
            async: true,
            crossDomain: true,
            success: function (data) {
                resolve(data);
            },
            error: function (err) {
                reject(error);
            }
        });
    });
}
async function handler() {
    try {
        var data = await hit_db();
        return data;
    }
    catch (error) {
        throw new Error('Network call failed');
    }
}
return handler();

Side Note: I have already solved any possible CORS issues with my ajax call

megs56
  • 41
  • 7
  • 1
    Try returning the resolve: `return resolve(data);` in the `success` handler. – Kevin Boucher May 29 '18 at 20:09
  • what happens when you replace `return data` with `console.log(data)`? – raina77ow May 29 '18 at 20:09
  • 3
    This is expected per [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then). Maybe you want `.done()`, which returns the *deferred* object? – Tyler Roper May 29 '18 at 20:09
  • probably you have an error and it never resolves, add `.catch` after `.then` – Taki May 29 '18 at 20:10
  • @raina77ow console.log(data) returns the desired output to the console – megs56 May 29 '18 at 20:11
  • What version of jQuery are you using? – charlietfl May 29 '18 at 20:11
  • 3
    *"I thought that once the promised was fulfilled I could return data which is the server response"* No, that's not how promises work. You can only get the resolved value in a `.then` callback. The caller of `hit_db` has to be aware that the function returns a promises. `hit_db().then(data => /* do something with data */)`. Promises do *not* make you asynchronous code synchronous. They just provide a unified API for handling async values. – Felix Kling May 29 '18 at 20:11
  • @charlietfl Those are ES6 promises, not jquery promises. – J. Pichardo May 29 '18 at 20:12
  • 3
    @J.Pichardo I understand that but this also also a deffered promise anti-pattern since in jQuery v3+ $.ajax returns a Promises A+ compliant promise – charlietfl May 29 '18 at 20:13
  • @TylerRoper what happens when I use `.done()` ? and how would I implement it ? my ultimate goal is to have my code return `data` that is first referenced in `success` – megs56 May 29 '18 at 20:14
  • @megs56: That's not possible. `hit_db` can only return a promise. Related: [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321/218196) – Felix Kling May 29 '18 at 20:14
  • 2
    @kevin why?!?!?! – Jonas Wilms May 29 '18 at 20:19
  • So, what you're saying is, it's doing exactly what it's supposed to do? – Kevin B May 29 '18 at 20:19
  • So then how could I possibly get `data` to return? @FelixKling – megs56 May 29 '18 at 20:24
  • I already answered that in my first comment: The **caller** of `hit_db` has to be aware that the function returns a promise. The caller is then responsible for unwrapping the promise via `hit_db().then(data => ...)`. – Felix Kling May 29 '18 at 20:25
  • Sorry it might be because I dont quite get the `=>` syntax but I'm still getting `obj Promise` returned. I'm quite new to javascript so I would really appreciate the guidance @FelixKling – megs56 May 29 '18 at 20:45
  • `hit_db().then(function(data) { /* do something with data */})`. Have a look at the duplicate question. Getting a promise as return value is expected. There is no way around that. I have explained everything in the comments (and in the duplicate already). Take your time to read and understand it. – Felix Kling May 29 '18 at 21:06

1 Answers1

0

You are returning hit_db().then(...). The return value of .then(...) is a promise. The level of "unnesting" that you want to achieve is not possible.

As Gustavo said, this would require async/await.

With promises you could do chaining to simplify async workflow

hit_db()
  .then(...)
  .then(...)
  .then(...)
  .catch(...)
lipp
  • 5,586
  • 1
  • 21
  • 32