Hi
I have a provider for the http requests and a provider for a class called sections (to fetch the data and so on). the problem is that when I use the http provider to create the request the sections method will execute the next line without waiting even though it is an async method !
here is my http provider method :
sendGetRequest(url){
this.storage.get('token').then((val) => {
this.token = val
let link = Constants.API_ENDPOINT+url;
return new Promise((resolve, reject)=>{
this.http.get(link,{},{Authorization: "Bearer "+val})
.then(data =>{
var res = JSON.parse(data.data);
resolve(res.data);
})
.catch(error =>{
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
});
});
}
and here is the sections loading method :
async loadSections(){
this.sections = await this.httpProvider.sendGetRequest("/v1/owner/section/list");
// the following line returns "undefined" and does not wait for the previous line to finish
console.log(await this.sections);
}
Maybe it’s because you didn’t pack everything in the new promise. Also you forgot to handle the error in the new promise
sendGetRequest(url){
// ****** Pack the all return in the new promise ******
return new Promise((resolve, reject)=>{
this.storage.get('token').then((val) => {
this.token = val
let link = Constants.API_ENDPOINT+url;
this.http.get(link,{},{Authorization: "Bearer "+val})
.then(data =>{
var res = JSON.parse(data.data);
resolve(res.data);
})
.catch(error =>{
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
// ****** Also don't forget the error ******
reject(error);
});
});
});
@keloa: That’s really bad code. I know a lot of tutorials are written that way, and it probably isn’t your fault. But don’t trust web tutorials! The new Angular Http Module makes this soooo much easier. Read this, and your life will improve. You only need one or two lines of code.
With Ionic 3, it’s Angular best practices, unless you’re using HTML, in which case find Ionic blogs you trust. I think @joshmorony and @javebratt are consistently good bloggers. But for something that doesn’t draw on the screen, like an http get, the official Angular tutorials and style guide are the most up to date information.