Skip to content

Instantly share code, notes, and snippets.

@dart200
Last active July 13, 2020 09:17
Show Gist options
  • Save dart200/9d29930b60909fad774af4591185ea1a to your computer and use it in GitHub Desktop.
Save dart200/9d29930b60909fad774af4591185ea1a to your computer and use it in GitHub Desktop.

right now, i'm writing some promise code that looks like this. i need to both store the unsubscribe function returned from the subcribtion, as well as wait for the subscriber callback to run once before proceeding, and it looks pretty ugly:

let chatLoaded = false; // don't start loading messages until chat info has loaded
await new Promise(resolve =>
  unsubs.push(
    chatRef.onSnapshot(
      doc => {
        uiStore.receiveChat(doc.data());

        if (!chatLoaded) {
          chatLoaded = true;
          resolve();
        }
      },
      err => unexpectedError('Chat info loading failure', err.message),
    )
  )
);

i would much prefer to write it like this:

const chatLoaded = new Promise();
const chatUnsub = chatRef.onSnapshot(
  doc => {
    uiStore.receiveChat(doc.data());
    if (!chatLoaded.resolved)
      chatLoaded.resolve();
  },
  err => unexpectedError('Chat info loading failure', err.message),
);
unsubs.push(chatUnsub);
await chatLoaded;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment