Middle
Implement a function promiseWithResolver (deferred promise) that returns an object with resolve and promise fields.
sobes.tech AI
Answer from AI
The promiseWithResolver function creates a deferred promise, returning an object with the promise itself and a function to resolve it (resolve). This is useful when you need to control the resolution of the promise from outside.
Example implementation in JavaScript:
function promiseWithResolver() {
let resolve;
const promise = new Promise(res => {
resolve = res;
});
return { promise, resolve };
}
// Usage:
const deferred = promiseWithResolver();
deferred.promise.then(value => console.log('Resolved with:', value));
deferred.resolve('Success');
In this example, resolve is accessible from outside, and we can call it at any time to resolve the promise.