Use Promise.withResolvers to wrap callbacks
Use Promise.withResolvers to await the result of a callback-driven operation and handle success or cancellation with the same promise.
A dialog sends its answer to a callback, but the code that opened it needs to await that answer. The callback may run after the function has returned. Promise.withResolvers() lets you hand back the waiting promise and keep its settlement functions in the callbacks that need them.
Give each operation its own promise
Suppose an existing picker calls onPick with a file name or onCancel if the reader closes it. Wrap that interface where you call it. Save this as picker.mjs and run it with Node 22. A timer simulates the picker returning a file name.
function chooseFile(openPicker) {
const { promise, resolve, reject } = Promise.withResolvers()
try {
openPicker({
onPick: resolve,
onCancel: () => reject(new Error('Picker cancelled')),
})
} catch (error) {
reject(error)
}
return promise
}
const selected = await chooseFile(({ onPick }) => {
setTimeout(() => onPick('report.csv'), 0)
})
console.log(selected)
try {
await chooseFile(({ onCancel }) => onCancel())
} catch (error) {
console.log(error.message)
}The first call prints report.csv after the timer callback. The second prints Picker cancelled because the cancellation callback rejects its promise.
Promise.withResolvers() packages the promise and the same resolve and reject functions you get inside a promise constructor executor. It creates the promise before you wire up the picker. The call to openPicker can invoke a callback at once or retain it to call after a click.
Settle every terminal path
The try block covers a picker that throws while you open it. The rejection callback handles cancellation reported by the picker. If your picker has a separate asynchronous error callback, pass reject there too. A throw from a callback on a later tick escapes the try around openPicker.
If the picker reports two results, the first settlement call wins in this example. It passes either a string to resolve or an error to reject, so the promise settles on that call. If none of the callbacks run, the promise stays pending. Wire every exit from the picker, including a close button, to one of those paths.
Create the promise inside chooseFile so opening the picker again gives the caller a new result to await. If your picker exposes subscriptions, remove them when the operation finishes. Settling a promise has no effect on event listeners the picker registered.