0

I first wrap JQuery ajax like this:

function Ajax(settings) {
  let p = $.ajax(settings).then(
    (data, textStatus, jqXHR) => ({ data, textStatus, jqXHR }),
    (jqXHR, textStatus, errorThrown) => { throw ({ jqXHR, textStatus, errorThrown }); });

  return Promise.resolve(p);
}

I also have:

function to (promise) {
  return promise
    .then(data => [null, data])
    .catch(err => [err, undefined])
}

I then do:

const [arr, res] = await to(Ajax(...));
if (err) return;
let d = res.data;

Which works well.

However I then tried like this:

async function Await(promise) {
  return await promise
   .then(data => [null, data])
   .catch(err => [err, undefined]);
}

and

const [arr, res] = Await(Ajax(...));
if (err) return;
let d = res.data;

I can see the Ajax runs and Await then clause gets called with the correct object however I then get:

unncaught (in promise) TypeError: Await is not a function or its return value is not iterable

What is wrong here ?

kofifus
  • 17,260
  • 17
  • 99
  • 173
  • your `Await` function returns a Promise, as does **every** `async` function, since that's the by-product of the `async` tag, it basically forces the function to return a Promise, since the function is no longer a `Function` but an `AsyncFunction`, which always returns a Promise ... and a Promise is not iterable, therefore the error is that `return value is not iterable` – Jaromanda X Jun 06 '23 at 09:48
  • Why `return Promise.resolve(p);` instead of `return p`? – Quentin Jun 06 '23 at 09:52
  • 1
    @Quentin - wouldn't that ensure you return an actual promise, rather than whatever jquery pretends to be a promise (especially older versions of jquery) – Jaromanda X Jun 06 '23 at 09:53
  • 1
    what you're trying to do is flawed .... you seem to think you can break out of the Promise paradigm, you can't, asynchrony remains asynchronous, and must be used correctly, like `const [arr, res] = await to(Ajax(...));` ... no reason to further encapsulate that in some function thinking it'll suddenly become synchronous – Jaromanda X Jun 06 '23 at 09:55

0 Answers0