Async Fetch then Close Window - javascript

I am trying to use an asynchronous function to perform a POST request. Once this request has been sent, I wish to close the current window. Below is the code I am using.
async function postData() {
const response = await fetch(destinationUrl, fetchOptions);
return response.json();
}
postData().then(window.close());
The parts work individually, but when combined, the request doesn't seem to be sent before the window closes.
How can I make sure the request is sent before closing the window?
I would like to avoid the use of a timeout if possible.

You have to provide a callback to .then:
async function postData() {
const response = await fetch(destinationUrl, fetchOptions);
return response.json();
}
postData().then(() => window.close());
// or more concise:
postData().then(window.close);

Related

How can I wait all XHR request to be loaded?

I have a method for our website's search field.When I type a word into search field, server gives me a response.These responses sometimes can be a log so I have to wait for all XHRs to be loaded not a specific response.Tried waitForLoadState seems not working.Tried below code but it only returned one response not other requests?
async searchTextWithWait(value: string) {
await(await this.page.waitForSelector("//span[contains(#class,'search-input')]/input")).type(value,{delay:80})
await this.page.waitForResponse(response => {
return response.status() == 200
});
}
Maybe this solution can help you:
const selector = "//span[contains(#class,'search-input')]/input";
await this.page.locator(selector).waitFor();
await Promise.all([
this.page.waitForLoadState('networkidle'), // wait until there are no network connections for at least 500 ms.
this.page.locator(selector).type(value,{delay:80}),
]);

Request data from server when other response complete in JavaScript

I requesting the server(written in Node.js) using "fetch-api" function of javascript. I want to make multiple request to the server When the user clicks a button.
Is there such a way in JavaScript ?
When the server responds. Then the second request Send.
And when second response come.
Third request send and so on...
Please help me . Thanks in advance!
the fetch function returns a promise.
you need to await it like so:
await fetch('http://test.com/1');
await fetch('http://test.com/2');
await fetch('http://test.com/3');
you can also access the responses like so:
const res1 = await fetch('http://test.com/1');
const data1 = await res1.json();
if (data1.foo == '123') {
await fetch('http://test.com/2');
await fetch('http://test.com/3');
}

Playwright's page.waitForResponse gets wrong response

I'm trying to make assertions on XHR, but can't find a right way on how to grab the correct request.
The task is simple: click a button, then wait for network request and make assertions on it's response and request bodies.
The problem is that before I call changePageSize() function in my tests, there are already multiple requests in my network with the exact same URLs and methods. The only difference between them is request and response body, so it happens that my code just grabs the first request that matches url I provided. Is there an any way on how to specify the exact network request that I want to use in my tests?
Here is the function:
static async changePageSize(selector: string): Promise<any> {
const [resp]: any = await Promise.all([
page.waitForResponse(`**${paths.graph}`),
this.setPagination(selector),
]);
return [resp]
}
And then I'm using it in my tests:
const [response] = await myPage.changePageSize(selector);
expect(await response.text()).toContain(`${size}`);
expect(response.request().postData()).toContain(`${size}`);

Fetch API: how to wait until the whole response is downloaded without consuming it?

I have a utility method in my React app for making HTTP requests.
The method implements fetch timeout using AbortController.
What I'd like to get as a return value is a fully resolved Response. Here's my definition:
calling any method on this resolved response object should not result in network packets being sent or received. Plus, the body of this response should not be consumed.
Here's what I'm doing right now (not sure about this):
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
const response = await fetch(url, { signal: controller.signal })
const clone = response.clone();
// a call to initiate body transfer via network
const text = await clone.text();
clearTimeout(timeoutId);
return response;
When I call response.json() afterward, what exactly will happen? Will there be any network communication?

nodejs retrieve body from inside request scope

I'm new to nodejs and javascript in general. I believe this is an issue with the scope that I'm not understanding.
Given this example:
...
...
if (url == '/'){
var request = require('request');
var body_text = "";
request('http://www.google.com', function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
body_text=body;
});
console.log('This is the body:', body_text)
//I need the value of body returned from the request here..
}
//OUTPUT
This is the body: undefined
I need to be able to get the body from response back and then do some manipulation and I do not want to do all the implementation within the request function. Of course, if I move the log line into:
request( function { //here })
It works. But I need to return the body in some way outside the request. Any help would be appreciated.
You can't do that with callbacks because this will works asynchronously.
Work with callbacks is kind of normal in JS. But you can do better with Promises.
You can use the request-promise-native to do what you want with async/await.
async function requestFromClient(req, res) {
const request = require('request-promise-native');
const body_text = await request('http://www.google.com').catch((err) => {
// always use catches to log errors or you will be lost
})
if (!body_text) {
// sometimes you won't have a body and one of this case is when you get a request error
}
console.log('This is the body:', body_text)
//I need the value of body returned from the request here..
}
As you see, you always must be in a function scope to use the async/await in promises.
Recommendations:
JS the right way
ES6 Fetures
JS clean coding
More best practices...
Using promises

Categories