Unable to find a solution for Promise object

I am implementing chained Fetch to fetch images relevant to the articles. Initially, I retrieve the titles of the articles and then utilize the Unsplash API to obtain the appropriate images.

The issue arises when I receive my result not as an object, but only as a promise. My goal is to fill the div with the "results" id containing the object returned from the async function within the cards variable. Despite trying to incorporate Timeout, the outcome remains unchanged.

async function getPrograms(params) {
    url = 'http://127.0.0.1:8000/articles/api/?'
    url2 = 'https://api.unsplash.com/search/photos?client_id=XXX&content_filter=high&orientation=landscape&per_page=1&query='

    const program = await fetch(url + params).then(response => response.json());
    this.program = program;


    const cards = await program.results.map(async result => {
        // Objects that I need to populate card. Ex. title, description, date updated etc. Additionally, including images below (solely returning images for testing):
        let images = await fetch(url2 + result.title).then(response => response.json())
        return images
        });
    this.cards = cards;


    const printAddress = async () => {
        const a = await cards;
        return a
    };
    document.getElementById('results').innerHTML = printAddress()
};

Note: Despite referring to tutorials and Stack Overflow answers, I have yet to find a suitable solution to my problem.

Answer №1

Don't assume your mapped promises will be awaited as expected. Opt for using Promise.all instead:

const items = await Promise.all(data.listings.map(async item => {
    const response = await fetch(url + item.id);
    return response.json();
}));

Answer №2

When you use an async function within your map(), it's important to remember that Async Functions always return a promise. This means you must handle the promise outside of the function, typically using a combination of then() and catch().

const cards = await program.results.map(async result => {
    // Here, you populate card objects such as title, description, date updated, etc. In this example, only images are returned for testing:
    let images = await fetch(url2 + result.title).then(response => response.json())
    return images; // This returns a promise
});

cards.then(data=>{
    console.log(data); // You can access the data here
    this.cards = data; 
}).catch(()=>{
    console.log("Error"); 
});

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

I would like to smoothly fade in and out the text within the anchor tag, creating a subtle and gentle effect

My bootstrap navigation bar has icons that transition to text when hovered over, but the change is too abrupt. I would like it to appear more smoothly and gradually, similar to the effect on this website This is an example of my HTML code: <nav cla ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

Combine multiple arrays containing observables into a unified array

I am facing the challenge of flattening a nested Observable into a single observable array. The Observable looks like this: Observable<Observable<any[]>[]> values; The inner arrays have the following structure: [ {id: 0, name: 'a'} ...

Creating a seamless integration of elements from two Vue.js components

As I work on developing the checkout page for an e-commerce app, I encounter the need to display a list of OrderItems from the database, each with its price and quantity. These items can be selected and grouped together. Additionally, I must also include a ...

Node.js: Using a for loop to iterate through a JSON array and extract all unique identifiers

I am encountering an issue with extracting the different ids from my json object. The only id I seem to be able to retrieve is that of the last item. Below is the function in question: var xmlhttp = new XMLHttpRequest(); var url = "https://wjko5u2865 ...

Having trouble accessing properties in AngularJS

This is my code snippet: app.controller('userController', function UserController($scope, userFactory) { $scope.users = []; $scope.user = { items : [] }; $scope.editMode = false; $scope.addItem = function () { $scope.use ...

How can one address the issue of undefined data within table cells?

I have encountered an issue while reading and displaying an XML file on a webpage using a JavaScript script. The problem arises when the page loads, and the information inside the cells of the table shows as "UNDEFINED". The intended display should include ...

arrange list in Angular.js

Currently, I am attempting to sort an array using Angular JS with the orderBy function. However, I am experiencing difficulties sorting it based on a specific key. Below is the code snippet: var app = angular.module('sortModule', []) app.contr ...

You are limited to using a maximum of two custom tags within a custom div

I came up with this code that is supposed to style the elements differently based on their tag names. However, when I tested it, the styling did not work as expected. For example, 'London' should be displayed as a large and bold h1 text, while th ...

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...

Can the tooltip on c3 charts be modified dynamically?

Creating a c3 chart involves defining various properties, including a tooltip. Here is an example: generateData = () => { const x = randomNR(0, 100); const y = randomNR(0, 100); const together = x + y; return { data: { columns: [ ...

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

What causes the discrepancy in the output values of the sha1 algorithm when using the packages object-hash and crypto/hashlib

On my frontend, I have implemented a JavaScript function that compares two sha1 hashes generated by the object-hash library. This is used to determine if there are any changes in the input data, triggering a rerun of a processing pipeline. To interact wit ...

Is the vertex count of a Geometry in Three.js increased when it is converted to a BufferGeometry?

Recently, I've been experimenting with the fromGeometry method to convert regular Geometry objects into BufferGeometry objects. To my surprise, I noticed that the number of vertices increases during this conversion process. For instance, consider the ...

Attempting to display my ejs template from a node server following the activation of a delete button, all without utilizing ajax

I have created a basic blog application using node.js for the backend and ejs for the frontend. Posting blogs using a web form works well by calling a post route. Now, I am facing an issue with implementing a delete button for each blog post. The current s ...

The file object appears to be empty when attempting to send it to the server using ng

Using ng-file-upload, I am attempting to upload a single file to my server. After selecting the file and passing the file object ($scope.myFiles[0]) to my angular service, I noticed that when inspecting the HTTP request in the developer tools, the file ob ...

Verify that the input is zero and then proceed to deactivate the submit button if it is indeed zero in AngularJS

app.controller('HelloController', function($scope) { console.log($scope.input1); console.log($scope.input2); if (($scope.op_option == 4) && ($scope.input2 == 0)) { myForm.$invalid; } }); <form id="calc" method="pos ...

How to pass hidden values in an HTML form

There is a hidden HTML element within a form that looks like this: <input type="hidden" name="Something" id="Something" value="<?php echo "somevalue";?>"/> A JavaScript function changes the value of this hidden element. The question is: after ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...

Discover the sub strings that fall between two specified regular expressions

I am looking for a way to extract substrings from a string that are between two specified regex patterns. Here are a few examples: My $$name$$ is John, my $$surname$$ is Doe -> should return [name, surname] My &&name&& is John, my & ...