I have two ajax post request which need to be executed as synchronous calls.
Scenario is that the form is creating two differnt type of objects, these objects need to be sent to the different API as post request and I have to show animation on the UI until both API returns result to UI.
Any Help!
Edit to add Code
doApproveSingle() {
//animation part
this.loading = true
//call 1
this._http.post('api/single', this.approvedChanges, contentHeaders).subscribe(resp => {
}, error => {
})
//call 2
this._http.post('api/new', this.approveNew, contentHeaders).subscribe(resp => {
}, error => {
})
}
there are two post requests I need to close that animation after both calls are completed, need help in that part.
doApproveSingle() {
//animation part
this.loading = true
//call 1
let obs1 = this._http.post('api/single', this.approvedChanges, contentHeaders)
.map(resp => { ... });
//call 2
let obs2 = this._http.post('api/new', this.approveNew, contentHeaders)
.map(resp => { ... });
Observable.zip([obs1, obs2]).subscribe(val => this.loading = false);
}
If there is nothing to do when the individual HTTP calls complete, the .map(...) parts can be omitted.
Related
I want to execute the multiple times same API with different payloads, but it's not working.
it('call same api with different payload',()=>{
cy.intercept('PATCH', `**/user/1`,{name:'thava'} ).as("action1")
cy.intercept('PATCH', `**/user/1`,{name:'prakash'} ).as("action2")
cy.visit('../app/intercept-identical.html');
cy.get("#update-action1").click();
cy.wait(['#action1']);
cy.get("#update-action2").click();
cy.wait(['#action2']); // not working
})
When requests are identical, only one intercept routeMatcher will catch all the calls.
To vary the response, one way is to respond with a function
it('responds to identical requests with different responses', () => {
let requestNo = 0
const responses = [ { name: 'thava' }, { name:'prakash' } ]
cy.intercept('PATCH', '**/user/1', (req) => {
req.reply(responses[requestNo++])
}).as('action');
cy.visit('../app/intercept-identical.html')
cy.get("#update-action").click()
cy.wait('#action')
.its('response.body.name')
.should('eq', 'thava') // passes
cy.get("#update-action").click()
cy.wait('#action')
.its('response.body.name')
.should('eq', 'prakash') // passes
})
Tested with
<body>
<button id="update-action" onclick="clickhandler()"></button>
<script>
function clickhandler() {
fetch('https://jsonplaceholder.typicode.com/user/1', {
method: 'PATCH'
})
.then(res => res.json())
}
</script>
</body>
Note
req.reply(res => { res.send(...) } will not stub the request, it will only modify the response from the live server. If the server targeted is not able to accept 'PATCH', you will get an error.
Overriding intercepts
If you update to the latest version of Cypress, you can simply over-write the intercept.
The last-added intercept will be the one to catch the request.
it('overrides intercepts', () => {
cy.visit('../app/intercept-identical.html')
cy.intercept('PATCH', `**/user/1`, { name:'thava' } ).as("action1")
cy.get("#update-action").click()
cy.wait('#action1')
.its('response.body.name')
.should('eq', 'thava') // passes
cy.intercept('PATCH', `**/user/1`, { name:'prakash' } ).as("action2")
cy.get("#update-action").click()
cy.wait('#action2')
.its('response.body.name')
.should('eq', 'prakash') // passes
})
Hi i am working on my Angular 7 project. I am getting one response from a api and i want to integrate that response to other api which result success in all other apis.
Here is my code :
ngOnInit() {
this.second()
}
first() {
this.service.getId(id).resp.subscribe((res => {
console.log(res);
this.firstresp = res;
});
}
second() {
this.service.getId(this.firstresp).resp.subscribe((res => {
console.log(res)
});
}
Here the problem is first function executed properly and second function i am getting response only after refreshing the page. Any solution? TIA.
This is actually an RXJS question, not an angular one. You want to use switchMap:
this.service.getId(id).resp.pipe(
switchMap((res) => {
return this.service.getId(res).resp;
})
).subscribe((rep) => {
....
});
switchMap above pipes the result of the first call into the second one then emits that result to the subscribe. No need for the firstresp etc.
My PWA has a large data payload. I want to display a 'Please wait...' load page and wait until all caching is complete before launching the full app. Therefore, I need to detect when all caching has completed. The snippet of my service worker is:
let appCaches = [{
name: 'pageload-core-2018-02-14.002',
urls: [
'./',
'./index.html',
'./manifest.json',
'./sw.js',
'./sw-register.js'
]
},
{
name: 'pageload-icon-2018-02-14.002',
urls: [
'./icon-32.png',
'./icon-192.png',
'./icon-512.png'
]
},
{
name: 'pageload-data-2019-02-14.002',
urls: [
'./kjv.js'
]
}
];
let cacheNames = appCaches.map((cache) => cache.name);
self.addEventListener('install', function (event) {
console.log('install');
event.waitUntil(caches.keys().then(function (keys) {
return Promise.all(appCaches.map(function (appCache) {
if (keys.indexOf(appCache.name) === -1) {
caches.open(appCache.name).then(function (cache) {
return cache.addAll(appCache.urls).then(function () {
console.log(`Cached: ${appCache.name} # ${Math.floor(Date.now() / 1000)}`);
});
});
} else {
console.log(`Found: ${appCache.name}`);
return Promise.resolve(true);
}
})).then(function () {
// Happens first; expected last.
console.log(`Cache Complete # ${Math.floor(Date.now() / 1000)}`);
});
}));
self.skipWaiting();
});
When I test this with a simulated 3G network, the trace is:
I do not understand why the 'Cache Complete' message is logged before any of the individual 'Cached' messages are logged; I would expect it to be last. Is there something different about the way Promise.all behaves compared to other promises?
Oy! What a silly oversight. After breaking the promise chains into individual promises and stepping through the code, the problem became obvious.
self.addEventListener('install', function (event) {
console.log('install');
event.waitUntil(caches.keys().then(function (keys) {
return Promise.all(appCaches.map(function (appCache) {
if (keys.indexOf(appCache.name) === -1) {
// Never returned the promise chain to map!!!
return caches.open(appCache.name).then(function (cache) {
return cache.addAll(appCache.urls).then(function () {
console.log(`Cached: ${appCache.name} # ${Math.floor(Date.now() / 1000)}`);
});
});
} else {
console.log(`Found: ${appCache.name}`);
return Promise.resolve(true);
}
})).then(function () {
console.log(`Cache Complete # ${Math.floor(Date.now() / 1000)}`);
});
}));
self.skipWaiting();
});
I never returned the promise chain to the map function (no explicit return always returns undefined). So the array passed to Promise.all contained only undefined values. Therefore, it resolved immediately and hence logged its message before the others.
Live and learn...
#claytoncarney Do you know how to pass a callback.. or any way to listen to this event from my app?
I try to send a toast message to my user telling them that the data has been cached...
In this case, I send an alert (it's do not work)...
I have written the following code, it runs smoothly but I have encountered a question:
submitFormToBackend = async () => {
if (this.paymentMethod === 'apple-pay') {
this.setState({ showLoadingIndicator: true }); // <-- below await setTimeout can confirm this line run before it
}
let requester = new ApplePayRequester({...this.form});
let applePay = new ApplePay();
await setTimeout(async () => {
let cardTokenResponse = await applePay.getCardToken();
if (cardTokenResponse.isSuccess()) {
requester.setCardToken(cardTokenResponse.message);
let response = await requester.pushToBackend();
this.setState({ showLoadingIndicator: false }); //<-- below setTimeout can confirm this line run before them
if (response.isSuccess()) {
setTimeout(() => { this.navigator.backToPreviousScreen(); }, 800);
} else {
setTimeout(() => { Alert.alert('your purchase has error. Try again'); }, 800);
}
} else {
this.setState({ showLoadingIndicator: false });
setTimeout(() => { Alert.alert('cannot get your card token.'); }, 800);
}
}, 800);
};
My render() in that component:
render() {
return (
<View style={styles.form}>
<LoadingIndicator visible={this.state.showLoadingShader} />
<InputBox />
<InputBox />
<SubmitButton />
</View>
);
}
As you see there are a lot of setTimeout() functions, it seems like functions will crash together if I don't use setTimeout() to restrict the functions run one by one.
However, it's not a good practice as there is no default millisecond for success running (the millisecond can set to 700ms or 1500ms or etc.). Therefore I would like to ask is there any solution to confirm previous function has run before next function start, other than using setTimeout()?
UPDATE
Procedures:
Step 1 - Press submit button
Step 2 - Pop up a confirmation modal
Step 3 - User confirm, dismiss confirmation modal, set showLoadingIndicator to true to show loading indicator
Step 4 - Call ApplePay and pop up ApplePay UI
Step 5 - User confirm, set showLoadingIndicator to false to dismiss loading indicator and navigate previous screen
Problems encountered when not using setTimeout():
Step 4 - ApplePay UI cannot pop up after setting showLoadingIndicator to true, below is the code that encountered problem:
let cardTokenResponse = await applePay.getCardToken();
Step 5 - Alert will be pop up before setting showLoadingIndicator to false, which stops the setting, below is the code that encountered problem:
this.setState({ showLoadingIndicator: false });
if (response.isSuccess()) {
} else {
setTimeout(() => { Alert.alert('your purchase has error. Try again'); }, 800);
}
A second optional parameter of setState function is a callback function that runs synchronously with the state change.
So you can just rely on the following:
this.setState({
//change state variables here
}, () => {
//do the next work here...
});
The callback function always run post the state is changed.
In your code, this would work:
this.setState({ showLoadingIndicator: false }, () => {
if (response.isSuccess()) {
this.navigator.backToPreviousScreen();
} else {
Alert.alert('your purchase has error. Try again');
}
});
I need to call an API recursively using request promise after getting result from API need to write in an excel file , API sample response given below
{
"totalRecords": 9524,
"size": 20,
"currentPage": 1,
"totalPages": 477,
"result": [{
"name": "john doe",
"dob": "1999-11-11"
},
{
"name": "john1 doe1",
"dob": "1989-12-12"
}
]
}
Now I want to call this API n times, here n is equal to totalPages, after calling each API I want to write response result to the excel files.
First write page 1 response result to excel then append page 2 response result to excel file and so on..
I have written some sample code given below
function callAPI(pageNo) {
var options = {
url: "http://example.com/getData?pageNo="+pageNo,
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
json: true
}
return request(options)
}
callAPI(1).then(function (res) {
// Write res.result to excel file
}).catch(function (err) {
// Handle error here
})
But facing problem calling recursively API and maintaining sequentially like write page 1 result first to excel file then page 2 result append to excel and so on..
Any code sample how to achieve in nodejs
You want to do something like this:
function getAllPages() {
function getNextPage(pageNo) {
return callAPI(pageNo).then(response => {
let needNextPage = true;
if (pageNo === 1) {
// write to file
} else {
// append to file
}
if (needNextPage) {
return getNextPage(pageNo+1);
} else {
return undefined;
}
});
}
return getNextPage(1);
}
Obviously change that 'needNextPage' to false to stop the recursion when you're done
So you want to do 477 requests in sequence? How long do you wanna wait for this to finish? Even in paralell, this would be still too long for me.
Best: write an API that can return you a batch of pages at once. Reducing the number of requests to the backend. Maybe something like http://example.com/getData?pages=1-100 and let it return an Array; maybe like
[
{
"totalRecords": 9524,
"currentPage": 1,
"totalPages": 477,
"result": [...]
},
{
"totalRecords": 9524,
"currentPage": 2,
"totalPages": 477,
"result": [...]
},
...
]
or more compact
{
"totalRecords": 9524,
"totalPages": 477,
"pages": [
{
"currentPage": 1,
"result": [...]
},
{
"currentPage": 2,
"result": [...]
},
...
]
}
Sidenote: writing the size of the results array into the json is unnecessary. This value can easily be determined from data.result.length
But back to your question
Imo. all you want to run in sequence is adding the pages to the sheet. The requests can be done in paralell. That already saves you a lot of overall runtime for the whole task.
callApi(1).then(firstPage => {
let {currentPage, totalPages} = firstPage;
//`previous` ensures that the Promises resolve in sequence,
//even if some later request finish sooner that earlier ones.
let previous = Promise.resolve(firstPage).then(writePageToExcel);
while(++currentPage <= totalPages){
//make the next request in paralell
let p = callApi(currentPage);
//execute `writePageToExcel` in sequence
//as soon as all previous ones have finished
previous = previous.then(() => p.then(writePageToExcel));
}
return previous;
})
.then(() => console.log("work done"));
or you wait for all pages to be loaded, before you write them to excel
callApi(1).then(firstPage => {
let {currentPage, totalPages} = firstPage;
let promises = [firstPage];
while(++currentPage < totalPages)
promises.push(callApi(currentPage));
//wait for all requests to finish
return Promise.all(promises);
})
//write all pages to excel
.then(writePagesToExcel)
.then(() => console.log("work done"));
or you could batch the requests
callApi(1).then(firstPage => {
const batchSize = 16;
let {currentPage, totalPages} = firstPage;
return Promise.resolve([ firstPage ])
.then(writePagesToExcel)
.then(function nextBatch(){
if(currentPage > totalPages) return;
//load a batch of pages in paralell
let batch = [];
for(let i=0; i<batchSize && ++currentPage <= totalPages; ++i){
batch[i] = callApi(currentPage);
}
//when the batch is done ...
return Promise.all(batch)
//... write it to the excel sheet ...
.then(writePagesToExcel)
//... and process the next batch
.then(nextBatch);
});
})
.then(() => console.log("work done"));
But don't forget to add the error handling. Since I'm not sure how you'd want to handle errors with the approaches I've posted, I didn't include the error-handling here.
Edit:
can u pls modify batch requests, getting some error, where you are assigning toalPages it's not right why the totalPages should equal to firstPage
let {currentPage, totalPages} = firstPage;
//is just a shorthand for
let currentPage = firstPage.currentPage, totalPages = firstPage.totalPages;
//what JS version are you targeting?
This first request, callApi(1).then(firstPage => ...) is primarily to determine currentIndex and totalLength, as you provide these properties in the returned JSON. Now that I know these two, I can initiate as many requests in paralell, as I'd want to. And I don't have to wait for any one of them to finish to determine at what index I am, and wether there are more pages to load.
and why you are writing return Promise.resolve([ firstPage ])
To save me some trouble and checking, as I don't know anything about how you'd implement writePagesToExcel.
I return Promise.resolve(...) so I can do .then(writePagesToExcel). This solves me two problems:
I don't have to care wether writePagesToExcel returns sync or a promise and I can always follow up with another .then(...)
I don't need to care wether writePagesToExcel may throw. In case of any Error, it all ends up in the Promise chain, and can be taken care of there.
So ultimately I safe myself a few checks, by simply wrapping firstPage back up in a Promise and continue with .then(...). Considering the amounts of data you're processing here, imo. this ain't too much of an overhead to get rid of some potential pitfalls.
why you are passing array like in resolve
To stay consistent in each example. In this example, I named the function that processes the data writePagesToExcel (plural) wich should indicate that it deals with multiple pages (an array of them); I thought that this would be clear in that context.
Since I still need this seperate call at the beginning to get firstPage, and I didn't want to complicate the logic in nextBatch just to concat this first page with the first batch, I treat [firstPage] as a seperate "batch", write it to excel and continue with nextBatch
function callAPI(pageNo) {
var options = {
url: "http://example.com/getData?pageNo="+pageNo,
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
json: true
}
return request(options)
}
function writeToExcel(res){console.log(res)} //returns promise.
callAPI(1).then(function (res) {
if(res){
writeToExcel(res).then(() => {
var emptyPromise = new Promise(res => setTimeout(res, 0));
while(res && res.currentPage < res.totalPages){
emptyPromise = emptyPromise.then(() => {
return callAPI(res.currentPage).then(function (res){
if(res){
writeToExcel(res)
}
});
}
}
return emptyPromise;
});
}
}).catch(function (err) {
// Handle error here
})