I've been trying different ways of resolving a Promise with inconsistent results. I've included two code snippets, and I'm unsure of what is happening differently so that the first resolves successfully while the second fails.
In this first attempt, I include an IIFE in the Promise, and the IIFE recognizes resolve
despite the fact that I didn't pass this into the function itself. The result is "test"
being successfully logged to the console:
const testFunction = function() {
return new Promise(function(resolve) {
!function() {
resolve();
}();
});
};
!async function() {
await testFunction();
console.log('test');
}();
In the next example, I created a separate function which is called within the Promise
. However, this other function doesn't seem to know what resolve
is unless I define the function to take a parameter and then pass resolve
through later on. This version below does not work:
const printSomething = () => {
resolve();
}
const testFunction = function() {
return new Promise(function(resolve) {
printSomething();
});
};
!async function() {
await testFunction();
console.log('test');
}();
I expected that since printSomething
is running within testFunction
, just as the IIFE was, that resolve
would be available. Any explanation to clear this up would be helpful. Apologies in advance if this is actually a failure of understanding scope in general and not specific to Promises.