Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
JavaScript Dynamic Promises

I am trying to understand how promises work in JS by playing with swapi.dev. I would like to create a dynamic chain of promises (not using async/await) but it does not provide me with any result. In particular, the idea behind is to get all names of the given person (for instance Luke Skywalker) and dump them into the console.

Could anyone help me? What am I missing?

Thanks in advance.

"use strict";

const request = require("request-promise");
const BASE_URL = "http://swapi.dev/api";

var currentPromise = Promise.resolve();

callApiPromise(`${BASE_URL}/people/1`).then((data) => {
  console.log("Getting vehicles' URLs");
  const vehicles_URL = data["vehicles"];

  console.log("Starting looping through URLs");
  for (let i = 0; i < vehicles_URL.length; i++) {
    console.log(`i=${i}, vehicle_URL=${vehicles_URL[i]}`);
    currentPromise = currentPromise.then(function () {
      console.log(".. getting vehicle name");
      return getVehicleName[vehicles_URL[i]];
    });
  }
});

function getVehicleName(url) {
  callApiPromise(url).then((vehicle_data) => {
    var arrVehicleData = new Array();
    arrVehicleData.push(vehicle_data);
    console.log(arrVehicleData.map((vehicle) => vehicle.name));
  });
}

function callApiPromise(url) {
  return new Promise((resolve, reject) => {
    callApi(url, (err, data) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(data);
    });
  });
}

function callApi(url, callback) {
  request
    .get(url)
    .then((response) => {
      const json = JSON.parse(response);
      callback(null, json);
    })
    .catch((err) => {
      callback(err, null);
    });
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Some issues:

  • A missing return statement in getVehicleName
  • A syntax issue in getVehicleName[vehicles_URL[i]] (should be parentheses)
  • As the promises for getting the vehicle names are independent, you would not chain them, but use Promise.all
  • arrVehicleData will always only have one element. There is no reason for an array there where it is used.

You are also taking the wrong approach in using request.get. The bottom function turns that API from a Promise-API to a callback API, only to do the reverse (from callback to promise) in the function just above it. You should just skip the callback layer and stick to promises:

"use strict";

const request = require("request-promise");
const BASE_URL = "http://swapi.dev/api";

getJson(`${BASE_URL}/people/1`).then(data => {
  return Promise.all(data.vehicles.map(getVehicleName));
}).then(vehicleNames => {
  console.log(vehicleNames);
  // Continue here...
});

function getVehicleName(url) {
  return getJson(url).then(vehicle => vehicle.name);
}

function getJson(url, callback) {
  return request.get(url).then(JSON.parse);
}

Finally, you should not use request-promise anymore since the request module, on which request-promise depends, has been deprecated

about 4 years ago · Juan Pablo Isaza Report

0

The getVehicleName doesn't return a promise. Instead it invokes a promise that by the time it will be resolved, the for loop invoking it will already be removed from the call stack.

This is a sample of promise chaining:

const promise = new Promise(resolve => resolve(1))
const promise1 = Promise.resolve(2)
const methodReturnPromise = () => new Promise(resolve => resolve(3))

promise.then(firstPromiseData => {
  // do something with firstPromiseData
  console.log(firstPromiseData)
  return promise1
}).then(secondPromiseData => {
  // do something with secondPromiseData
  console.log(secondPromiseData)
  return methodReturnPromise()
}).then(thirdPromiseData => { 
  // do something with thirdPromiseData
  console.log(thirdPromiseData)
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!