I'm struggling with a block of code involving closures in a set of promises. This example illustrates the problem. The issue is getting the last of these three promise examples to have a closure on q
and use the result of the promise. The first two work and it appears to be because the promises' success handlers are just the closure function without any other argument, meaning the result of the promise isn't explicitly passed as an argument. The success function of the third promise attempts to pass a property of the result object but that results in there not being a closure on q
. The objective is to have q
be 5 and not 7. I apologize because I am sure I've used all the wrong coding terms.
Could you please explain what I am missing? Thank you.
let q = 1;
let f = (function (x) {
return function (r) {
result(x, r);
}
})(q);
q = 5;
promise_test().then((r) => {
f(r);
}, () => { });
promise_test().then((function (x) {
return function (r) {
result(x, r);
}
})(q), () => { });
promise_test_obj().then((o) => (function (x) {
return function (r) {
result(x, r);
}
})(q)(o.m), () => { });
q = 7;
function promise_test() {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve('promise test resolved');
}, 100);
});
}
function promise_test_obj() {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve({ 'm': 'promise test_obj resolved' });
}, 100);
});
}
function result(a, r) {
console.log('q : ' + a + ', r : ' + r);
}