From 0bc97bd90283ed79052fb6f56926253b210b881c Mon Sep 17 00:00:00 2001
From: Yarmo Mackenbach <yarmo@yarmo.eu>
Date: Thu, 25 Mar 2021 16:28:56 +0100
Subject: [PATCH] Improve promise handling

---
 src/fetcher/matrix.js  | 24 +++++++++++++-----------
 src/fetcher/twitter.js | 36 +++++++++++++++++++-----------------
 2 files changed, 32 insertions(+), 28 deletions(-)

diff --git a/src/fetcher/matrix.js b/src/fetcher/matrix.js
index 141e0c2..c0be324 100644
--- a/src/fetcher/matrix.js
+++ b/src/fetcher/matrix.js
@@ -27,18 +27,20 @@ module.exports = async (roomId, eventId, opts) => {
 
   const url = `https://${opts.instance}/_matrix/client/r0/rooms/${roomId}/event/${eventId}?access_token=${opts.accessToken}`
 
-  const fetchPromise = bentReq(url, null, {
-    Accept: 'application/json',
+  const fetchPromise = new Promise((resolve, reject) => {
+    bentReq(url, null, {
+      Accept: 'application/json',
+    })
+      .then(async (data) => {
+        return await data.json()
+      })
+      .then((data) => {
+        resolve(data)
+      })
+      .catch((error) => {
+        reject(error)
+      })
   })
-    .then(async (data) => {
-      return await data.json()
-    })
-    .then((data) => {
-      return data
-    })
-    .catch((error) => {
-      return error
-    })
 
   return Promise.race([fetchPromise, timeoutPromise]).then((result) => {
     clearTimeout(timeoutHandle)
diff --git a/src/fetcher/twitter.js b/src/fetcher/twitter.js
index 169c6a2..2f1a993 100644
--- a/src/fetcher/twitter.js
+++ b/src/fetcher/twitter.js
@@ -25,23 +25,25 @@ module.exports = async (tweetId, opts) => {
     )
   })
 
-  const fetchPromise = bentReq(
-    `https://api.twitter.com/1.1/statuses/show.json?id=${tweetId}&tweet_mode=extended`,
-    null,
-    {
-      Accept: 'application/json',
-      Authorization: `Bearer ${opts.bearerToken}`,
-    }
-  )
-    .then(async (data) => {
-      return await data.json()
-    })
-    .then((data) => {
-      return data.full_text
-    })
-    .catch((error) => {
-      return error
-    })
+  const fetchPromise = new Promise((resolve, reject) => {
+    bentReq(
+      `https://api.twitter.com/1.1/statuses/show.json?id=${tweetId}&tweet_mode=extended`,
+      null,
+      {
+        Accept: 'application/json',
+        Authorization: `Bearer ${opts.bearerToken}`,
+      }
+    )
+      .then(async (data) => {
+        return await data.json()
+      })
+      .then((data) => {
+        resolve(data.full_text)
+      })
+      .catch((error) => {
+        reject(error)
+      })
+  })
 
   return Promise.race([fetchPromise, timeoutPromise]).then((result) => {
     clearTimeout(timeoutHandle)