1

I have tried the usual Promise.all but I get a circular Json error. I have the following promises in my console

all [ Promise { <pending> }, Promise { <pending> } ]
all [ Promise { <pending> } ]
all [ Promise { <pending> } ]
all [ Promise { <pending> } ]

With the following code

const needle = require("needle");

const token = process.env.BEARER_TOKEN_TWITTER;

const endpointUrl = "https://api.twitter.com/2/tweets/search/recent";

export default async function login(req, res) {
  try {
    

    const all = req.body.map((item) => {
      const params = {
        query: `"$${item.title}" from:${item.twitter}`,
      };

      return needle("get", endpointUrl, params, {
        headers: {
          "User-Agent": "v2FullArchiveJS",
          authorization: `Bearer ${token}`,
        },
      }).catch((err) => {
        console.warn(err);
      });
    });


    console.log("all", all);
    // Update
    console.log("allll", await Promise.all(all));


    const result = await Promise.all(all);

    res.status(200).json({ authenticated: true, result: result });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}

I have read the following with no luck

How to do promise.all for array of array of promises?

Front End Call

const fetchData = async () => {
      const response = newArray.map(
        async (question) => {
          console.log("question", question.data);
          return await fetchTweets(question.data);
        }
      );

      console.log("response", response);


      
      const promise4all = await Promise.all(
        response
        );
        console.log("promise4all", promise4all);
      // setTweets(await Promise.all(response));
    };

enter image description here

Anders Kitson
  • 1,413
  • 6
  • 38
  • 98
  • it's quite large but I get about 4 of these, which usually I can just get the body but when I try to access the body I get undefined I am not sure how I got the ciruclar Json actually I deleted what I did there Here is what needle returns tho https://gist.github.com/anderskitson/8e656a0d80d924dd3f3cd06250e6688c – Anders Kitson Feb 23 '22 at 05:36
  • or actually, you can `const result = await Promise.all(all);` ... then use `result` for res.json rather than `all` – Bravo Feb 23 '22 at 05:36
  • `"here is what needle returns"` ... no, it returns a Promise - read the documentation - you have to deal with promises using .then or await in your case – Bravo Feb 23 '22 at 05:37
  • yeah I had done that and you see the output I get above – Anders Kitson Feb 23 '22 at 05:37
  • no I don't ... you console.log of all does NOT mean you've `await Promise.all(all)` at all ... `all` remains unchanged, it's the result of awaiting it that you need ... the code you've written does not use Promise.all so don't say you've done that since you have not – Bravo Feb 23 '22 at 05:38
  • `console.log("allll", await Promise.all(all));` this returns what is in the gist, but I can't access the body if it – Anders Kitson Feb 23 '22 at 05:38
  • I've told you how .... `const result = await Promise.all(all)` ... then use `result` ... **not `all`** - `all` is an array of promises ... it never changes ... `Promise.all(all)` doesn't change `all` – Bravo Feb 23 '22 at 05:39
  • 1
    You could also do `res.status(200).json({ authenticated: true, result: await Promise.all(all) });` - if you want the values, await the promises that resolve them - every time (or once and store results in a variable like my first suggestion) - awaiting a variable that is a promise does not change the variable from a promise to a resolved value - awaiting returns the resolved value – Bravo Feb 23 '22 at 05:43
  • I added the code changes, but I still get this circular json because whatever is getting passed to front end is still 4 promises they never get resolved, I don't quite understand what is going on – Anders Kitson Feb 23 '22 at 05:49
  • 1
    then you're doing it wrong – Bravo Feb 23 '22 at 05:50
  • suddenly it's the front end with the error? what data does `fetchTweets` return – Bravo Feb 23 '22 at 05:52
  • it's not suddenly, it's been both the whole time fetchTweets return 4 promises. Anyways I got to sleep, thanks for your help. I'll figure it out in the morning – Anders Kitson Feb 23 '22 at 05:54
  • oh, but this is new code (fetchData), I thought it was the old code (login) that had the issue - what is `fetchTweets` function and what does it do – Bravo Feb 23 '22 at 05:55
  • Don't swallow the needle error. Either delete the `.catch()` clause or rethrow after logging. – Roamer-1888 Feb 24 '22 at 05:33

1 Answers1

0

Had to do the following

const needle = require("needle");

const token = process.env.BEARER_TOKEN_TWITTER;

const endpointUrl = "https://api.twitter.com/2/tweets/search/recent";

export default async function login(req, res) {
  try {
    const all = req.body.map((item) => {
      const params = {
        query: `"$${item.title}" from:${item.twitter}`,
      };

      return needle("get", endpointUrl, params, {
        headers: {
          "User-Agent": "v2FullArchiveJS",
          authorization: `Bearer ${token}`,
        },
      }).then(function (response) {
        return response.body;
      });
    });


    const result = Promise.all(all);


    res.status(200).json({ authenticated: true, result: await result });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}

front end

useEffect(() => {
    // declare the async data fetching function
    const fetchData = async () => {
      const response = newArray.map(
        async (question) => {
          console.log("question", question.data);
          return await fetchTweets(question.data);
        }
      );

      setTweets(await Promise.all(response));
    };

    if (data) {
      fetchData();
    }

  }, [data]);
Anders Kitson
  • 1,413
  • 6
  • 38
  • 98