Wait for the HTTP request to be completed to continue the rest of the script in Angular
You can use operators like this:
getData(fId: string | null = null) {
return this.getDataFromAPI().pipe(
tap(data => {
this.tempItems = [data]
}),
map(data => {
let items = cloneDeep([data]);
// Separate the items by folders and files
const a: Item[] = items.filter(item => item.type === 'a');
const b: Item[] = items.filter(item => item.type !== 'b');
const path: Item[] = [];
//do some work
// Create data
return {
folders: a,
files: b,
path
};
}),
tap(data => {
this._items.next(data);
})
);
}
tap
is used to apply side effects and doesn't change the emitted valuemap
is used to transform the emitted value
Angular wait for multiple http requests to complete
ForkJoin actually accepts an array of observables parameter so you could do something like this.
const arr = [this.data.getCodes('medical'), this.data.getCodes('delay')];
//add more observables to your arrays
arr.push(this.data.getCodes('disability'));
//use spread operator on subscribe response
forkJoin(arr).subscribe(([...arrayResp])=>{
//arrayResp will contain array of response
let theFirstResponse = arrayResp[0];
});
wait for http.request response before executing further
UPDATE:
Try this way of wrapping your httpsRequest in a promise. The main method here is the method your switch statement is embedded in.
const respCode = 11;
async function main() {
var responseCode = await new Promise(res => {
httpsRequest(res);
});
// now you have responseCode from outside the callback
console.log(responseCode);
}
// function with the similar signature to https.request
function httpsRequest( /*other args, */ callback) {
// mock your http request with the constant respCode from above
setTimeout(() => {
callback(respCode);
}, 1000);
}
main();
how to wait for Http request complete?
You need to put your for
loop into the .then()
handler of the first HTTP request. That way it will be executed after your request finishes, not in parallel to it:
fetch('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1')
.then(response => response.json())
.then(data => {
console.log(data.deck_id);
const deckId = data.deck_id;
for(let i = 0; i < 2; i++) {
for (let x = 0; x < players.length; x++) {
fetch('https://deckofcardsapi.com/api/deck/' + deckId + '/draw/?count=1')
.then(response => response.json())
.then(data => {
console.log(data.remaining);
const deckLength = data.remaining;
data.cards.map((card) => {
var newCard = getCardData(card);
players[x].Hand.push(newCard);
renderCard(newCard, x);
updatePoints();
updateDeck();
});
});
}
}
});
How to wait for a http request to finish from another component?
You could expose the authentication information in a BehaviorSubject
:
class AuthenticationService {
private subject = new BehaviorSubject(null);
public info = subject.asObservable();
authenticate() {
this.http.get<AuthInfo>('.../Auth/login').subscribe(x => this.subject.next(x), e => this.subject.error(e))
}
}
Call authenticate
wherever you need in your app (e.g: on a login button)
Then I suggest you to use an interceptor in order to make sure that requests are authenticated before they are sent:
class AuthenticationInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return authenticationService.info.pipe(
tap(x => /* If you need to attach the JWT to an HTTP header, do it there */),
switchMap(() => next.handle(req))
)
}
}
How to wait until a HTTP request is complete to finish function
Ok, there is multiple ways to do this. You can use async/await and promises for that. You can read about them on the web - it's pretty easy. Here is draft example:
function search(productCategory, productId) {
// Here you return new promise
return new Promise((resolve, reject) => {
// Here you do your code and after it completes - resolve result
var options = {
"method": "GET",
"hostname": 'HOSTNAME',
"path": [
"PATH",
],
"headers": {
"x-api-key": "API_KEY",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
var result = JSON.parse(body);
var id = result.result[0].value;
// console.log(id);
//
// Here you RESOLVE promise result
resolve(id);
});
});
req.end();
});
}
And in caller function you modify it to be async and add await before calling promise function
// Add async before function to handle await method
module.exports = async getId(req, res) {
var categoryId = "";
var productId = '';
var posId = "";
for(var i=0; i < req.body.result[0].products.length; i++){
categoryId = req.body.result[0].products[i].category_id;
productId = req.body.result[0].products[i].product_id;
// Add await to PAUSE execution of this function and wait
// the result from search promise
posId = await search(categoryId, productId);
var product = {
"product number": i,
"product_category": categoryId,
"product_id": productId,
"posId": posId
};
productsArray.push(product);
}
res.send(JSON.stringify(orderingProducts));
};
Related Topics
Querying in Firebase by Child of Child
Ios-Charts Set Maximum Visible X Axis Values
Swiftui Behavior of .Frame(Height: Nil)
How to Make Prepareforsegue with Uicollectionview
How to Create a Portal Effect in Arkit Just Using the Scenekit Editor
Handling an Attribute of an Xml Element in Swift
Moving Skspritenode to Location of the Touch
Fail to Import Restkit with Cocoapods Dynamic Frameworks
Which Value Types in Swift Supports Copy-On-Write
How to Await X Seconds with Async Await Swift 5.5
Swift: How to Create a Predicate with an Int Value
Realm Swift: Always Put Nil Values Last in Sort
Disable Bounce Scrolling for Wkwebview in MACos
How to Properly Check If Non-Optional Return Value Is Valid
Swift Programmatically Create Function for Button with a Closure