jQuery “promises” are not real promises and never will be due to backwards compatibility issues. reference:
var jQueryPromise = $.ajax('/data.json');
var realPromise = Promise.resolve(jQueryPromise);
//now just use `realPromise` however you like.
The Promise API is incredibly important for any JavaScript programmers that will be dealing with asynchronous calls, which means probably every JS web developer. Thus, it’s worth spending some time on this.
I think that the article We have a problem with promises is very good. I just fixed one of my promises to actually be a chained correctly. It is easy to verify by checking the stack in Chrome DevTools.
Here’s my full async/await example (from the es6fiddle):
var longFn = function(x) {
return new Promise(function(res, rej) {
if (x) {
setTimeout(res(x), 1000);
} else {
rej("ERROR from not passing in a value to longFn");
}
});
};
async function f(inputToAsync) {
console.log("f() starting with param: ", inputToAsync);
let result;
try {
result = await longFn(inputToAsync);
} catch (err) {
console.log("THROWING err: " + err);
throw err;
}
return "RETURN VALUE FROM ASYNC function: " + inputToAsync;
}
var p = f("INPUT TO ASYNC FUNCTION");
console.log("1: return value of async function is ", p);
p.then(
res => console.log("1: FINISHED: got back: " + res)
).catch(
err => console.log("1: GOT ERROR: err")
);
var p = f(false);
console.log("2: return value of async function is ", p);
p.then(
res => console.log("2: FINISHED: got back: " + res)
).catch(
err => console.log("2: GOT ERROR: err")
);