Saturday 26 September 2020

Making concurrent API calls in node.

Hey guys. I'm new to node and I'm having trouble with it.I have an array of numbers like [1,2,3,1,2,3] and I want to make simultaneous post requests to an api using this data. For example, [1,2,3] and then [1,2,3].I also want 1 to be completely processed before 2, 2 to be processed before 3, so on and so forth. And the first batch to be processed before the second one.How do I go about that? I found Async utility module and I'm trying to use that, but I'm encountering a few problems.I'm getting the error: Error [ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client.They aren't being processed in order obviously. I don't know how to fix this.Anyways, here's my code. Sorry if this seems a little confusing. I'm a beginner.const axios = require("axios"); const numbers = require("../model/data"); // [1,2,3,4,5,6,7,8,9,10] const async = require("async"); exports.callAPI = (req, res, next) => { var queue = async.queue(function (number, callback) { axios .post("http://www.api.com/", { number: `${number}`, webhookURL: "http://localhost:8000/", }) .then(function (response) { res.send(response.data); }) .catch(function (err) { console.log("Err after api call", err); }); callback(); }, 3); // assign a callback queue.drain(function () { console.log("Finished api calls"); }); // assign an error callback queue.error(function (err, call) { console.error("Found an error"); }); // add some items to the queue numbers.forEach((number) => { queue.push(number, function (err) { if (err) { console.log(err); } }); }); };

Submitted September 27, 2020 at 01:06AM by CodeLiftRepeat

No comments:

Post a Comment