Retrieve the data stored within an [Object Promise] for further use

Having trouble utilizing a value retrieved from an API call.

Below is my TypeScript code:

 private async fetchPersonName() {
            let fullName = await Api.getName('Data($select=FullName)', `personId  eq ${currentPersonId}`);
            return fullName.value[0].Data.FullName;
        }

Now, I simply need to append it to the DOM using jQuery.

$("#myId").text(/*fetchPersonName() result*/);

Trying to append this displays [object Promise] in the DOM. Uncertain how to correctly employ this value.

Thank you.

Answer №1

Here is a suggestion to update the text of an element with id "myId" using the await keyword:

$("#myId").text(await getPersonName());

Alternatively, you can use the following function to fetch and display a person's full name based on their ID:

private async getPersonName() {
   let fullName = await Api.GetName('Data($select=FullName)', `PersonId  eq ${currentPersonId}`);
   return fullName.value[0].Data.FullName;
}

After defining the function, you can call it and update the element text like this:

getPersonName().then((value) => {
    $("#myId").text(value);
})

Answer №2

It's important to remember that getPersonName() is declared with the async keyword, so you need to use the await keyword when calling it.

var name = await getPersonName();
$("#myId").text(name);

You could also simplify it further like this:

$("#myId").text(await getPersonName());

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

Valid resource causes failure in cross-domain jQuery ajax call

One example shows an attempt to make a cross-domain call using jQuery.ajax(): <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script> <script> $(document).r ...

Ways to pause for the completion of multiple HTTP promises and display a modal exclusively when all promises result in failure

There are two separate HTTP calls on a page that need to be handled independently. vm.$onInit = function() { .... .... //Retrieve all items during initialization ds.getAllItems().then(function(result){ vm.items = result; },funct ...

What is the significance of property placement in a Mongo query: at the beginning versus at the

Currently, I am in the process of creating a query to retrieve data from the mango collection. Interestingly, I have written the same query in two different ways. Here is my working query: db.getCollection('routes').find({"routes.routeId": "r1q ...

Tips for creating a clickable title that directs to a URL

I am currently using the "Import All" WordPress plugin to bring in an Excel file containing numerous hyperlinks that point to specific Custom Post Types and a designated field. These hyperlinks are separated by commas from the corresponding title. For exam ...

Unable to locate module src/ in Node.js TypeScript

I'm encountering issues with non-relative imports in my node.js / typescript application. Here is my tsconfig: { "compilerOptions": { "target": "es6", "module": "commonjs", "lib": ["dom", "es6", "es2017", "esnext.asynciterable"], "s ...

Using jQuery to evaluate multiple conditions within an if statement

I'm working on a script that needs to continuously monitor for the presence of an input field with the class name "email" (as this content is loaded via AJAX). If this input exists, I need to show another input field with the class name of "upload". A ...

Having trouble rendering a private route screen in React, while all the other screens work perfectly

I am encountering an issue with my Private Route in React where it fails to render, while every other screen renders successfully. I have set up the Private Route to render my PrivateScreen.js component, everything seems to be set up correctly but I cannot ...

How can we transform the `toUSD(amount)` function into a prototype function?

This function is functioning perfectly as intended. function toUSD(amount): string { // CONVERT number to $0.00 format return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount); }; Here is how I currently i ...

What is the best way to implement a scroll-into-view feature for a newly added list item in Vue.js?

I am currently utilizing vueJS to create a task viewing application. My goal is to make the div containing the list focus on the newly added list item immediately after adding a new task. Here's the HTML code from my template for the task list: < ...

Exploring the Power of PrimeNG and Observables in Angular 4 with RxJS

After configuring my Angular 4 project with a service like this: const usersURL = 'http://my.super.url.php'; @Injectable() export class UserService { users: Observable<User[]> constructor (public http:Http) let tick$ = Observ ...

What is the best way to handle sequential $http calls in AngularJS? Specifically, I want to make the second $http call dependent on the response of the first

When making two $http calls, the second call should only be executed based on the response from the first call if there is an error present. ...

Encounter Issue: "Describe" function not recognized. This error occurred during the activation of Mocha Test

https://i.sstatic.net/WBSm6.png Upon my installation of mocha, I encountered an issue while running a test using a command, resulting in the error message "describe is not a function." ...

When clicking, populate the content of another div in a vertical top-to-bottom fashion

I am in the process of creating a functionality where clicking on one element will fill another element's content from bottom to top. Although I have managed to make it work on hover, the same functionality is not triggered when clicking on the eleme ...

Using THREE.js: Object3D Dimension Shrinkage

Is there a way to disable sizeAttenuation for an Object3D in THREE.js? I'm working on rendering a trajectory at a massive scale using arrow helpers to show the motion direction. I want the arrow heads to maintain their orientation without changing si ...

Learn how to organize a div element containing select options using categories such as gender and shoe size, similar to the filtering

Is there a way to sort div elements using a select menu, similar to how it is done on shopping websites? I am struggling with modifying my JS code in order to implement multiple selects. Although I believe my JS code is correct, it doesn't seem to be ...

Adding the most recent version of jquery causes the webpage to malfunction

Currently, I am facing a challenge on a website that has an outdated version of jQuery (1.7.2) included in the header. In order to use a plugin that requires the latest version of jQuery, I tried linking the newer version (2.1.3) in the footer. However, j ...

What steps can I take to enhance the resilience of my Node.js websocket socket.io server against DoS attacks?

Recently, I discovered that my project's WebSocket server, built in Node.js using socket.io, experienced an outage due to a front-end app entering a loop of malformed connection attempts rejected by the server. This caused the single Node.js CPU thre ...

Troubleshooting: jQuery Autocomplete not functioning correctly with dynamically generated form fields

Hey there! I'm facing a new issue that I need help with. Currently, I have implemented jquery Autocomplete on a form field and it's working perfectly! The problem arises when I dynamically add another row to the form. The autocomplete feature d ...

Discovering dynamic content enclosed by static values in Applescript

Just starting out with applescript and facing a challenge. I need to extract a string from a web page via Safari and assign it to a variable. The target string varies, but the words before and after it remain constant. For instance: Apple 1293.34 USD The ...

Obtain the currently selected HTML element using tinyMCE

Within my editor, I have the ability to choose text and show it using the code below: alert(tinyMCE.activeEditor.selection.getContent({format : "html"})); The problem is that this function only returns text and not HtmlElement. This means I am unable to ...