0

How can I create a promise which will never fulfil? So that for example this will never reach console.log:

const res = await NEVER_FULLFILLING_PROMISE

console.log(res)
Woww
  • 344
  • 2
  • 10
  • 3
    `new Promise(() => {})`, but why would you need this? – Sebastian Simon Mar 11 '22 at 01:31
  • @SebastianSimon its useful for Svelte, when you use the {await} block to wait for a promise, but the promise gets set onMount and since you cannot await an undeclared variable, you just create an unfulfillable promise at the beginning and override it onMount – Woww Mar 11 '22 at 01:36
  • 2
    Related: [What happens if you don't resolve or reject a promise?](https://stackoverflow.com/q/36734900/4642212). – Sebastian Simon Mar 11 '22 at 01:38

1 Answers1

2

Just call new Promise and never call the first parameter in the callback.

(async () => {
  await new Promise(() => {});
  console.log('done');
})();

Another approach that fulfills the text of your question (but probably not the intent) would be to make the Promise reject, of course.

(async () => {
  await new Promise((_, reject) => reject());
  console.log('done');
})()
  .catch(() => {});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320