I have the following block of code:
async done() => {
return new Promise((resolve, reject) => {
const events = new Map();
events.set('CLOSE_CLICK_EVENT', () => {
//other logic
resolve(false);
});
}
}
I am trying to removing the "other logic" to an external function. My other approach is below:
revised approach:
async done() => {
return new Promise((resolve, reject) => {
const events = new Map();
events.set('CLOSE_CLICK_EVENT', () => {
return this._doneCloseButtonHandler(events);
});
}
}
async _doneCloseButtonHandler(events) {
//other logic
return false;
}
The 2nd approach doesn't seem to be behaving the same way though -- why is the Promise being resolved differently? The Promise doesn't seem to be getting resolved when I try to use the 2nd approach.
CodePudding user response:
In the second approach, you are never calling the resolve
function, so it cannot resolve, you need to chain it:
return this._doneCloseButtonHandler(events).then(resolve, reject);
Edit: based on OP's request, there is also a way to resolve within the _doneCloseButtonHandler
function when you pass the resolve
as argument:
return this._doneCloseButtonHandler(events, resolve)
// ...
function _doneCloseButtonHandler(event, resolve) {
// ....
resolve()
}
CodePudding user response:
To extract the "other logic", you should first refactor your function to
async done() {
const _ = await new Promise((resolve, reject) => {
const events = new Map();
events.set('CLOSE_CLICK_EVENT', resolve);
// do something with `events`
});
// other logic that should happen when the CLOSE_CLICK event occurs
return false;
}
(the _
corresponds to whatever will be passed to the resolve
call).
Then you can extract the other logic into a separate function.