julianmp julianmp - 1 year ago 131
Javascript Question

Asynchronous / Synchronous Looping Node.js

Hi I'm trying to do something a little weird here it's kind of mixing async and sync together hence why it's not working how I expected. Currently runs for 3 users from the array then ends how would I get this to run for the entire length of the usernames in the array?

var i = 0,
fs = require('fs'),
fetch = require('node-fetch');

fs.readFile('file.txt', function(err, data) {
var array = data.toString().split("\n");

function getCreationDate(array) {
fetch('http://mytwitterbirthday.com/api/?screen_name=' + array[i])
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(i, array[i])
console.log(json[0].screen_name, json[0].created_at);
}).then(function() {

Answer Source

I assume you don't need to print the outputs in the same order as in the array. In this case you can change getCreationDate() to accept a single name and its index.

function getCreationDate(name, i) {
  fetch('http://mytwitterbirthday.com/api/?screen_name=' + name)
  .then(function(res) {
    var json = res.json();
    console.log(i, name)
    console.log(json[0].screen_name, json[0].created_at);

Now call the above function for each item in the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download