The promise function resolves with no value

Trying to understand the promise function but struggling with returning the value. Any help would be appreciated.

static getTrailer(movieId) {
    return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
        .then(response => {
            return response.json();
        })
        .then(responseJson => {
            if (responseJson.videos.results[0]) {
                Promise.resolve(responseJson.videos.results[0].key)
                    .then(result => {
                        console.log(result);
                        return result;
                    });
            } else {
                return Promise.reject(`Trailer is not found`);
            }
        });
}

Tried to retrieve the result here:

<p>${DataSource.getTrailer(this._movie.id).then(resultKey => {console.log("data is: " + resultKey)})}</p>

However, the resultKey always returns as undefined. Can someone guide me on how to resolve this issue?

Answer №1

As soon as responseJson.videos.results[0] is true, you should simply return the desired value instead of returning nothing, which leads to the promise being resolved as undefined.</strong>, so the promise resolves as undefined.</p>

<p>Why complicate things by utilizing <code>Promise.resolve
unnecessarily?

Avoid the unnecessary additional promise and directly return the value intended for resolving the then statement.

    .then(responseJson => {
        if (responseJson.videos.results[0]) {
            const result = responseJson.videos.results[0];
            console.log(result);
            return result;
        } else {
            return Promise.reject(`Trailer is not found`);
        }
    });

Answer №2

If you want to pass data along a promise chain, make sure to use the return statement (either explicitly or through an arrow function)

Here is a simple and clear example:

static retrieveTrailer(movieId) {
    return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
        .then(response => response.json())
        .then(responseJson => responseJson.videos.results[0].key) // Any errors encountered will be handled in the catch block below
        .catch(error => {
            // This block catches errors from previous stages of the Promise chain
            throw new Error(`No trailer found`); // Throwing an error is more efficient than using Promise.reject()
        });
}

Answer №3

No need to rely on promises to retrieve the key again.


static obtainTrailerKey(movieId) {
    return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
        .then(response => {
            return response.json();
        })
        .then(responseJson => {
            if (responseJson.videos.results[0]) {
                result = responseJson.videos.results[0].key;
                console.log(result);
                return result;
            } else {
                return Promise.reject(`Unable to find trailer`);
            }
        });
}

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

Acquiring the specific checkbox value using JQuery

I am encountering an issue with my JQuery function that is supposed to print out the unique value assigned to each checkbox when clicked. Instead of displaying the correct values, it only prints out '1'. Each checkbox is assigned an item.id based ...

Creating a login page with Titanium Appelerator is a breeze

Looking for guidance on creating a login page using Titanium Appcelerator docs. Struggling to grasp the documentation - any recommendations for tutorials on storing user data in a database, accessing it, and implementing a login system? ...

Combining Data Through Aggregation

Currently, I am in the process of developing a compact attendance system for educational purposes. Within this system, I am managing two important collections: Employee Information: { "id": "5f474ebb12a55e2a1c4fb39f", "emp ...

Utilize the onClick Event to Trigger Function with an Array in ReactJS

Every time I attempt to pass an array as a value to a function by clicking on a div, I encounter the error below: Uncaught Invariant Violation: Expected onClick listener to be a function, instead got a value of object type. If passing an array to a fun ...

When exporting an enum in StencilJS with TypeScript, the error "Cannot find name..." may occur

Looking for a solution: https://github.com/napolev/stencil-cannot-find-name In this project, there are two main files to consider: custom-container.tsx import { Component, Element, State } from '@stencil/core'; @Component({ tag: 'cu ...

The toggle for hiding and showing, along with changing the button color, is not functioning properly due to

I'm encountering a puzzling issue with a toggle that hides and displays information and changes color on click. The functionality works flawlessly on the page where I initially wrote the code. For instance, the button's background shifts colors w ...

The MVC framework causing the Morris chart to omit the final xkey value

I am facing an issue with my Morris Chart where it is not displaying the last xkey value. Any thoughts on why this might be happening? https://i.stack.imgur.com/mHBQd.png Here is the data I am working with: [{"Date":"2016-07-17","Average":0.0},{"Date":" ...

Ensuring compatibility of peerDependencies through devDependencies in npm3

With the recent update to NPM 3, automatic resolving of peer dependencies has been removed. This poses a challenge when developing a plugin/library for consumption by another application. If the underlying library uses peerDependencies, it requires manual ...

When attempting to click on another button, the action does not seem to be working as expected. The button in question has a

Greetings! I have encountered an issue where both of my buttons work perfectly fine individually, but when I attempt to use Button A to click Button B using JavaScript, it doesn't seem to work. I can confirm that Button A functions correctly as the al ...

Multi-line input in ExtJs

Is there a way to create a multiline input with vertical scrollbars in EXTJS? I tried the following code: noteField = new Ext.form.TextField({ emptyText: 'note...', multiline: true, applyTo: &apos ...

Avoid duplicating content when using Ajax to retrieve data in jQuery

Is there a solution when you click the button to display content, then click the button to hide it, and then click the button again to show it repeatedly? I'm not sure how to solve this issue. Can anyone help me out? Thank you! Here is the HTML code: ...

Step-by-step guide for transforming XML webservice output to JSON with the help of Express.js and Backbone.js

I'm new to Node.js and struggling with XML to JSON conversions I've tried several methods for converting XML to JSON, but none have met my requirements. Every conversion tool I've used seems to result in errors or missing elements that don& ...

Is it possible to establish a limit on a field's value in MongoDB?

Just a quick query - I'm curious if there's a feature in mongodb that allows for fields to have a set maximum value. For instance, let's say the field "cards" is restricted to a maximum value of 100. If an increment would exceed this limit, ...

Create an excel spreadsheet using HTML tables with the help of jQuery

Upon clicking a button, I aim to generate an excel sheet. Essentially, I am trying to achieve what is being discussed here (Kalle H. Väravas answer). If the following links are not working within Mozilla browser, then maybe my code requires ActiveXObject ...

The text/font-weight of the header button is mysteriously shifting without warning

While creating a header for my webpage, I encountered an issue where the text family was changing when the dropdown menu was launched in Safari 8. Curiously, this behavior did not occur when using Chrome to launch the jQuery function. Even after attempting ...

Using $.when with an Array of Promises

After searching for similar questions, I came across one that was almost exactly what I needed. However, it lacked error handling, which led me to encounter some issues while trying to implement it. My objective is to create a function that takes an array ...

Tips for setting the background image of the body once the image has finished loading

On my website, I have decided to incorporate high-resolution images as the background for the body. However, when I use document.body.style.backgroundImage = "url('URL OF PICTURE')";, the image loads vertically down the page which is not ideal. I ...

Dealing with errors in Node.js using the Express framework and the

The code I'm having trouble with is shown below app.get('/', function(req, res, next) { if (id==8) { res.send('0e'); } else { next(); } }); app.use(function(err, req, res, next){ res.send(500, ' ...

Leveraging mongo-triggers for automation

I just completed the installation of mongo-triggers by running: npm install mongo-triggers Now, I'm attempting to set up a simple "hello world" example: var MongoClient = require('mongodb').MongoClient; var triggers = require("mongo-trigg ...

Tips for incrementing a number by 1 at random intervals using jQuery

Is there a way to increase a number by 1 after an unpredictable delay? For instance, starting with a base value of 10, can we have it change by 1 after a random amount of time (e.g. between 1 and 5 seconds)? I attempted the following code: var ...