Fulfill the promise to retrieve the value contained within

Is there a way to use TypeScript to call the Wikipedia API for retrieving a random page title and save it in a variable for later use? I am struggling with resolving promises as I keep getting ZoneAwarePromise returned. I'm new to both promises and TypeScript, so any guidance on how to resolve this issue would be greatly appreciated.

I have attempted to add await to my promises, but I continue to encounter returned promises instead of the actual data.

async getPage() : string {
    var url = "https://en.wikipedia.org/w/api.php";
    var params = {
        action: "query",
        generator: "random",
        rnnamespace: "0",
        format: "json",
        list: "random",
        rnlimit: "1"
    };

    url = url + "?origin=*";
    Object.keys(params).forEach(function(key){url += "&" + key + "=" + params[key];});
    return await fetch(url)
        .then (response => response.json())
        .then(data => data.query.random[0].title)
        .catch(function(error){console.log(error);});
}

My goal is to extract the title from the retrieved data and store it in a variable for future use within other functions.

Answer №1

execute the following steps

async retrievePage() : string {
    var wikiUrl = "https://en.wikipedia.org/w/api.php";
    var parameters = {
        action: "query",
        generator: "random",
        rnnamespace: "0",
        format: "json",
        list: "random",
        rnlimit: "1"
    };

    wikiUrl = wikiUrl + "?origin=*";
    Object.keys(parameters).forEach(function(key){wikiUrl += "&" + key + "=" + parameters[key];});

    const pageTitle = await fetch(wikiUrl)
        .then(response => response.json())
        .then(data => data.query.random[0].title);
           .catch(function(err){console.log(err);});

   // perform operations with the retrieved title   

}

Answer №2

One important aspect of async functions is that they always return promises. The main purpose of using async/await is to simplify the syntax when working with promises. It's worth noting that combining async/await with .then is possible but generally not recommended as it can complicate code readability. It's advisable to stick to one style, preferably async/await.

Your getPage function should be structured similar to this:

async getPage(): string {
    let url = "https://en.wikipedia.org/w/api.php";
    const params = {
        action: "query",
        generator: "random",
        rnnamespace: "0",
        format: "json",
        list: "random",
        rnlimit: "1"
    };

    url = url + "?origin=*";
    Object.keys(params).forEach(function(key){
      url += "&" + key + "=" + params[key];
    });

    try {
      const response = await fetch(url);
      const data = await response.json();
      return data.query.random[0].title;
    } catch (error) {
       console.log(error)
    }
}

Keep in mind that getPage will result in a promise. To access the value within the promise, you can either use .then

getPage().then(title) => console.log('title', title));

or utilize async/await

async someFunction (){
  const title = await getPage();
  console.log('title', title);
}

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

What are the best practices for integrating QML with Java?

How can QML be interfaced with Java when developing the GUI and API for a linux based device? ...

Mysterious Angular Provider: $http

Is there a way to include the $http service in the config method? When I try to do so, I encounter an "unknown Provider" error message. This is the snippet of code causing the issue: .config(function($http, $routeProvider, $provide) { $http.get("samp ...

Trouble with X-editable: Unable to view values when editing and setting values using J

When using X-editable to modify a form with data, I encounter an issue. Initially, the values are loaded from the database to the HTML, but when users try to edit by clicking on the "Edit" button, all values appear as "Empty" instead of their actual cont ...

Pressing a key once causing two actions when managing content in a separate window

Issue: I am facing a problem where I receive double keypresses from one key event when the event updates content in two separate windows. (Please keep in mind that I am not an expert in this field and appreciate your understanding.) I am attempting to use ...

Retrieve information stored in a JSON data field within the results of an npm

How can I properly access the value of DepDateTime from the first object? Here is my current attempt: const nodeSkanetrafiken = require('node-skanetrafiken'); const from = { name: 'Bjärred centrum', id: 62025, type: 0 }; const to = ...

Error: The function props.addToCart is not accessible

While attempting to trigger my action on the client's click of the "addToCart" button to add a new product to the cart, I encountered the error message: "TypeError: props.addToCart is not a function." I am relatively new to Redux and have grasped the ...

Issue: The THREE.GLTFLoader cannot process this asset. Only glTF versions below 2.0 are compatible

Upon utilizing three.js, I encountered an error while parsing data from the GLTF JSON file. This file was exported from the three.js 3D viewer and editor, indicating a version of 4.5 in the JSON content. Highlighted below is the JSX code snippet: import { ...

Developing a innovative and interactive nested slider using Jssor technology

Trying to implement a dynamic jssor nested slider to showcase albums and images from a mySQL database. Everything works fine with a single album, but when there are two or more albums, the display gets messed up. I'm still learning JavaScript and JQue ...

Experimenting with a Collection of Items - Jest

I need to conduct a test on an array of objects. During the test coverage analysis of the displayed array, I found that the last object with the key link has certain conditions that are not covered. export const relatedServicesList: IRelatedServiceItem[ ...

What could be the reason for the sudden lack of content from the Blogger API?

For weeks, I've been using the Google API to retrieve JSON data from my Blogger account and showcase and style blog posts on my personal website. Everything was functioning flawlessly until yesterday when, out of the blue, the content section stopped ...

The issue with the Z-index being ineffective is causing the button to appear behind a container in the HTML-CSS

I am currently using Metro CSS (Windows 8 style) and running into an issue. Within my container, there are alerts displayed in blue, and above that is 'IT-CENTER'. When I click on 'IT-CENTER', a button should appear, but it seems to be ...

Scenario-specific blueprints

I'm currently facing a challenge in incorporating logic into a dustjs template, and I find it challenging to integrate all the components seamlessly. Here is an example of the JSON data I have: { "names": [{ "name": "User 1", "is ...

Which is the better option for opening a link in a button: using onclick or href?

What is the most effective way to open a link using a button? <button type="button" onclick="location='permalink.php'">Permalink</button> <button type="button" href="index.php">Permalink</button> ...

Tips on using the $.grep() method in jQuery to filter dynamic inputs

When using the "grep" function in jQuery to filter data, the code sample below works well for static conditions. However, if the "name" and "school" parameters have multiple values, how can we filter them? Let's say I receive the name and school from ...

Error message: While running in JEST, the airtable code encountered a TypeError stating that it cannot read the 'bind' property of an

Encountered an error while running my Jest tests where there was an issue with importing Airtable TypeError: Cannot read property 'bind' of undefined > 1 | import AirtableAPI from 'airtable' | ^ at Object.&l ...

Opacity effect on input text when it exceeds the input boundaries

I'm having an issue: I need to create inputs with different states, including when the text is longer than the input itself. In this case, the extra text should fade out with a gradient transparency effect: Here is my current code snippet: .Input { ...

Exploring the retrieval of specific values through bitwise operations in Angular

Currently, I am facing a challenge in retrieving a value that I had initially saved in the database as a sum of bits. My development work is based on Angular 9 using Typescript. I have successfully managed to store the sum of bits in the database. Now, I ...

What is the best way to delete a model from a Backbone.Collection?

How can I properly remove a model from a collection in Backbone.js? var item = new Backbone.Model({ id: "01", someValue: "blabla", someOtherValue: "boa" }); var list = new Backbone.Collection([item]); list.get("01").destroy(); After calling ...

What could be causing the background color not to change on the HTML page with Bootstrap?

Learning html, bootstrap, and css styling can be a confusing endeavor. Sometimes things don't work as expected, like changing the background color. Despite following what seems like a simple solution after googling, the background color remains unchan ...

Is there a suitable alternative that supports TypeScript, particularly with Angular 6, as D3Js does not directly support TypeScript?

I am currently engaged in a new project focusing on HR Analytics, utilizing Python, R, MySQL, and Angular 6 for the front end user interface. In terms of Data Visualization, I am exploring the use of D3js. However, it is important to note that D3Js does no ...