Here is an example of the code I am working with:
public getUrl(url) {
//returns URL
... }
public getResponseFromURL(): container {
let myStatus = 4;
const abc = http.get(url, (respon) =>
const { statusCode } = respon;
myStatus = statusCode;
console.log('Inside callback' +myStatus);
.on('error', (err) => {
console.log('Things have gone wrong' + err);
});
console.log('ITS COMPLICATED' +myStatus);
return new Container(status, body, header);
}
}
The main issue I am encountering is due to JavaScript's asynchronous behavior, where the console.log('ITS COMPLICATED') statement gets executed before the one inside the callback function. My goal is to ensure that the first console.log runs before the last one!
To address this, I implemented Async/Await as shown below:
public timeoutPromise(time: any) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Date.now());
}, time);
});
}
public doSomethingAsync() {
return this.timeoutPromise(1000);
}
Therefore, I modified my getResponseFromURL() method to make use of async/await like so:
public async getResponseFromURL(): Promise<container> {
this.myStatus = 7;
console.log(0);
await this.doSomethingAsync();
console.log(1);
const abc = http.get(url, (respon) => {
const { statusCode } = respon;
this.myStatus = statusCode;
console.log('Inside Callback ' + statusCode);
}).on('error', (err) => {
console.log('Things have gone wrong ' + err);
});
await this.doSomethingAsync();
console.log(2);
await this.doSomethingAsync();
console.log('Is it simple lalala ' + this.myStatus);
await this.doSomethingAsync();
}
}
However, a challenge arose when testing the async function and checking for the status property of the container class. Prior to
expect.getResponseFromURL().getStatus().toBe(200)
, I encountered issues.
The test scenario is outlined below:
test('Async function', async () => {
expect.assertions(1);
const data = await ContainerGlobals.getResponseFromURL().getStatus();
expect(data).toBe(207);
});
Presently, I am receiving an error related to .getStatus()
, and I'm unsure how to overcome this particular hurdle.
"does not exist on Promise"