Open a new tab when making an asynchronous API call

I'm having trouble with calling a function and opening a new tab in my VueJS application. Here is an example of what I want to do:

const someFunction = async () => {
   const value = await api.someCallToApi();
   window.open('https://example.com', '_blank').focus();
}

However, it seems like I can't do this because the window.open is not directly caused by a user action due to the use of await. The order of the api call and opening of the new tab matters for my application's functionality.

Is there a modern and effective alternative approach to solving this issue?

Answer №1

If we lived in a perfect world, every asynchronous function would be programmed to return promises automatically. However, there are still some outdated libraries that rely on the use of await. To work around this limitation, you can encapsulate the await function within a Promise like so:

const wait = (ms) => new Promise(resolve => setTimeout(resolve.bind(null, ms/1000), ms));


wait(3*1000).then((sec) => alert(sec + " seconds have elapsed"));

Answer №2

Trigger a click event programmatically following the completion of your API call:

const runFunction = async () => {
  const result = await api.makeApiRequest();
  const newLink = document.createElement('a');
  newLink.href = 'https://mywebsite.com';
  newLink.target = '_blank';
  newLink.click();
  newLink.remove();
}

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

Incorporate various pieces of information into an object

Hey everyone, I need some help with my ServiceNow code. I have a JavaScript doubt regarding it. I am attempting to display data in a marquee. <div> <marquee><b ng-repeat='val in data.arr'><label>{{val.display_field}}</ ...

The Gulp task abruptly terminates before the Stream has a chance to trigger the "end" event

const gulpJasmine = require('gulp-jasmine'); const gulpDebug = require('gulp-debug'); function runTest(platform, testType) { const timer = startTimer(); console.log('started!'); return gulp.src('./src/**/_test/**/ ...

Error: The call stack has reached its maximum size while running an npm install

Attempting to execute npm install, encountered the following console output: npm ERR! Linux 4.8.0-27-generic npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" npm ERR! node v6.9.1 npm ERR! npm v3.10.8 npm ERR! Maximum call stack size exceeded npm ...

Prevent strange appearances when using slideDown animation

In my application, I am experiencing an undesirable side effect when using slideDown(). Upon clicking the element, a piece of content is appended to an ancestor. This causes the clicked button to shift to the right and the ones on the left to move slightly ...

Creating a cutting-edge Windows Phone 8 application with JavaScript on Visual Studio 2013 Ultimate, recently updated to update 2

I am trying to create a windows phone 8 app using java-script in visual studio ultimate 2013 update 2, but I cannot seem to find the option for windows phone 8. Only the option for 8.1 is available. Can someone guide me on how to develop an app for windo ...

Leveraging require in AWS lambda operations

As part of my exploration into AWS Lambda functions, I've been trying to determine if the require statement can be used within them. This would allow me to incorporate other non-lambda functions into my code. Although zipping the node modules folder i ...

What web browsers encounter issues when storing XMLHTTPRequest responses in the cache?

Are there any potential issues with caching XMLHttpRequest responses in current browsers that I should take into consideration? I want to use XMLHttpRequest queries on each page to dynamically load relevant content (such as JSON) or behavior (like eval()e ...

The search function on my blog is not displaying the blogs that have been filtered

I have encountered an issue with my code as I am unable to get any search results from the search bar. const RecentBlogs = ({recentBlogs}) => { const [query, setQuery] = useState("") const filteredItems = (() => { if(!query) return rec ...

JQuery Ajax Json Feed Encountering Invalid Character Error

I'm using a JavaScript function to retrieve a Json Feed. function FetchCustomerDetails(CustomerNumber) { $.ajax({ url: "GetCustomerDetails.php", type: "GET", data:{CustomerNumber:CustomerNumber}, async: true, dataType: "json", success: function(Re ...

What is the best way to determine the total of values from user-input fields that are created dynamically

Scenario- A scenario where a parent component is able to create and delete input fields (child components) within an app by clicking buttons. The value of each input field is captured using v-model. Issue- The problem arises when a new input field is crea ...

OrbiterControls malfunctioning in a three.js application

I am attempting to set up a basic scene with an orbitercontrols feature that allows for rotation around the center, always facing (0,0,0). I would like it to function exactly like this . However, in my version, when I click and drag left or right, the ca ...

What is the solution for the error "this.$refs.[ref_name].save is not a function" in a component created with a "v-for" directive?

I'm currently developing a table list with some CRUD actions. Upon clicking the edit icon, a dialog box is opened containing 3 "v-tabs-items" generated through a "v-for". Within the last v-tab, there is an v-time-picker input within a menu, following ...

What is the purpose of the Condition being executed in the screep tutorial?

Lately, I've been heavily focused on Python programming but recently delved into the realm of Screeps and Javascript. As part of a tutorial, there is this code snippet that moves a creep towards an energy source to harvest it: if(creep.store.getFreeC ...

Passing information from Vue to a modal

I'm working with 3 components: TaskList, TaskItem, and TaskForm. Within the TaskList component, there is a loop that renders all the data in TaskItem. Each TaskItem has an edit button meant to open a TaskForm modal (using bootstrap) displaying the sp ...

Toggle the Material UI checkbox based on the value received from an object input

I am facing an issue with an unchecked checkbox in my project. I am attempting to update its value based on data retrieved from an object. The object contains boolean values from an SQL query, either 'T' for true or 'F' for false. My in ...

Guide on using Ajax to log a user in post-registration in Laravel 5.4

I am currently working on implementing a Modal registration box using Ajax. Everything is functioning properly, but I am facing an issue with logging the user in as well. Below is the modified register function in RegisterController.php: /** * Managing ...

Script CSP was declined from loading

After implementing CSP on my Nuxt website successfully, I encountered an issue when I added addMeta:true to the CSP object. This resulted in the following error message: https://i.sstatic.net/H5eTn.png Error message received: Refused to load the script ...

Unauthorized access for POST request in WooCommerce API: 401 error

Let's start by examining the complete code to better understand the issue at hand. Here is the WooCommerce API authentication using the consumer key and secret from the file checkout.ts: this.WooCommerce = WC({ url:"http://localhost/ ...

How can I implement a Dynamic Input field using Angular?

Suppose there is an input field where a user enters an ID. Once the user clicks the "add" button, I need to send a request to my server to fetch a "name". Afterwards, I want to disable the text input field, hide the "add" button, and show a number input fi ...

Updating the customer's billing address in Stripe without modifying their payment card details

Can I update a customer's stored address on Stripe without updating their card information as well? Currently, when customers update their info, they are required to enter their card details even for minor changes like the city. Is there a way to only ...