how to set a variable's value outside of a Promise using internal code

export class YoutubeService {

  getTrendingVideos(country) {
    let result = [];
    return axios.get('/').then(function(res){
      result = res.data.items;
      for (var i = 0; i < result.length; i++) {
        result[i] = {
          id: result[i].id,
          title: result[i].snippet.title,
          thumbnail: result[i].snippet.thumbnails.high.url,
          publishedAt: moment(result[i].snippet.publishedAt).fromNow()
        };
        result[i]= YoutubeService.getVideoDetails(result[i]).then(
            (video)=> 
              {
                  return video;
              }
        ); //result[i] is not getting resolved
        console.log(result[i]); // it returns Promise { <pending> }
      }
      return result;
    });

  }

  static getVideoDetails(video) {
    return axios.get('/').then(function(res) {
      let result = res.data;
      video.viewCount = result['items'][0].statistics.viewCount;
      video.likeCount = result['items'][0].statistics.likeCount;
      return video;
    });
  }
}

How can I set a value to 'result[i]' array from inside '.then()'? Currently, it is empty. The error returned is Promise { <pending> }. Thank you in advance.

Answer №1

Promise.all() resolves once an array of promises has all resolved successfully.

This snippet of code is designed to gather promises generated by the getVideoDetails() function and then create a promise that will handle all of those requests...

  getTrendingVideos(country) {
    let result = [];
    let promises = [];
    return axios.get('/').then(function(res){
      result = res.data.items;
      for (var i = 0; i < result.length; i++) {
        result[i] = {
          id: result[i].id,
          title: result[i].snippet.title,
          thumbnail: result[i].snippet.thumbnails.high.url,
          publishedAt: moment(result[i].snippet.publishedAt).fromNow()
        };
        promises.push( YoutubeService.getVideoDetails(result[i]) )
      }
      return Promise.all(promises);
    });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS $http.post triggers a 404 error indicating the status of the Express server

I recently set up separate ports for my express server and angular front end, using yeoman and grunt for the first time. This is my first experience working on a web project with this client/server structure, and I've encountered a challenge. On my f ...

Using hooks for conditional rendering

Background Information : My current project involves creating a form using hooks and rendering components based on the step. Challenge Encountered : I received this error message: "Error: UserFormHooks(...): Nothing was returned from render. This usually ...

Error in Chart.jsx: Unable to retrieve the length property of an undefined object in the COVID-19 Tracker App

INQUIRY Greetings, I am in need of assistance to identify an error that is perplexing me. The source of this code can be traced back to a tutorial on creating a covid tracker available on YouTube. While attempting to implement the chart feature, I encounte ...

Should commas be used in variables?

Could this be converted in a different way? $('#id').testfunction({ 'source' : [ {'source':'pathimage.jpg','title':'Title 1','description':'This is a description 1.'}, ...

Exploring the capabilities of TabrisJs in conjunction with Upnp technology

Working with Upnp in TabrisJs seems to be a bit challenging. Even though it has good support for node packages, I am facing difficulties while dealing with Upnp. I included node-upnp-client in my package.json file. "dependencies": { "tabris": "^2.0 ...

The shader on the background plane takes precedence over all other elements in three.js

I'm struggling to achieve a simple setup in my scene where a plane serves as the background with a shader, and a box is placed on top with a lambert material. Despite my efforts, I can't seem to make both the plane and the box appear together. An ...

Angular log out function to automatically close pop-up windows

Within my application, there is a page where users can open a popup window. When the user clicks on logout, it should close the popup window. To achieve this, I have used a static variable to store the popup window reference in the Global.ts class. public ...

Invoking a controller from another controller in the Express framework using Typescript

Currently, I am trying to call a controller from another controller in my code. While attempting to pass parameters using {params: {task_id: String(task_id), result}}, TypeScript is flagging an error indicating that res does not have all the required attri ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

JavaScript threw an error with message: 'Unexpected identifier' that was not caught

Upon launching Web Developer in Firefox: SyntaxError: missing } after property list note: { was opened at line 7, column 7 ...

Angular user profile update button not functioning as expected

We are currently implementing Angular alongside Node.js Express. Our issue arises when attempting to update user details from the settings page, as clicking the update button triggers the following error: Failed to load resource: net::ERR_CONNECTION_RESET ...

Can HTML/CSS be used to specifically target handheld mobile devices?

I am looking to optimize my video display in HTML by only showing it on desktop browsers. The difference in bandwidth between desktop and mobile devices is affecting the performance of mobile browsers, so I want to target only desktop users. Is there a way ...

Is there a way to activate ng-class on only a single element?

In my code, I am using ng-repeat and ng-class for each element to select elements and add borders for the selected ones. <div class="main-block_channel_create"> <section class="parent_messageList cancelDelete"> <div id="section_animate" ...

Does Javascript support annotation? If not, what is the best way to easily switch between debug and productive modes in a declarative manner?

I have a question that has been on my mind. I have searched Google but couldn't find any helpful links, so I thought it would be best to seek advice from experts here. My main concern is whether there is a way to create annotations in JavaScript sour ...

Displaying colors using Javascript

When using node.js to create an HTML file from a js file, I am encountering an issue where the colors are not displaying in the output. I have generated hex values for the colors, but they do not appear in the HTML file as expected. var format; function ...

JQuery GET brings back unnecessary HTML content

Currently utilizing a PHP cart class and implementing some jQuery to dynamically update a div when users add products. The issue I'm encountering is that upon adding a product, the list of products on the HTML page gets duplicated (see screenshot) ev ...

Secure authentication using hashed passwords for passport on an application programming interface

As I attempt to login on a /login route using passport, I provide an email and password (already stored in the database -email + hashed password with bcrypt). However, my code fails to enter the passport.use function... const passport = require("passport" ...

What is the best way to retrieve the input value from post.ejs?

app.js var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var passport = require('passport'); var localStrategy = require('passport-local'); var axios = require("axi ...

The straightforward To-Do application fails to display tasks

Does anyone have experience building a simple To-Do application using node js, express, mongodb, and ejs? I'm encountering an issue where although I can successfully save todos to my Mongo Compass database, they do not display on the screen as expect ...

Nesting placeholders is not permitted in i18n

I am attempting to implement Interpolation with Vue3 and vue-i18n version 9.3. However, when I try to pass arguments, I encounter the following error: Message compilation error: Not allowed nest placeholder 1 | Showing {{from}} to {{to}} of {{total}} ent ...