Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS await is not waiting for the request to finish

enter image description here

async function updateData(){
let stickTimes = [];
await request(terryRink, function (err, res, body) {
    if(err)
    {
        console.log(err, "error occurred while hitting URL");
    }
    else
    {
        let $ = cheerio.load(body);
        $('#ctl00_mainContent_ctl00_divContent > table > tbody > tr').each(async function(index){
            let date = $(this).find('td:nth-child(1)').text();
            date = date.split(', ')[1];
            const time = $(this).find('td:nth-child(2)').text();
            stickTimes.push({date: date, time: time, rink: 'Terry Connors'});
            console.log(stickTimes);
        });
    }
})

console.log(stickTimes);
return stickTimes;

}

Currently, I am trying to web crawl a website, add the data from it to an array, and then return that array. To wait, I am using async/await. Now, when I do await- it should wait until it is completed to run the code below, but it does not.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As seen the console.log, the below one is run before the one in the awaited request is run. [] is from the one on the bottom while the ones with data are from the one in the request itself

Why is this?

>Solution :

request function isn’t a promise, it is a callback async function, if you want to use async/await syntax, you need to convert it to promise.

async function updateData(){
let stickTimes = [];
const requestPromise = new Promise((resolve, reject) => {
  request(terryRink, function (err, res, body) {
    if(err)
    {
        reject()
    }
    else
    {
        let $ = cheerio.load(body);
        $('#ctl00_mainContent_ctl00_divContent > table > tbody > tr').each(async function(index){
            let date = $(this).find('td:nth-child(1)').text();
            date = date.split(', ')[1];
            const time = $(this).find('td:nth-child(2)').text();
            stickTimes.push({date: date, time: time, rink: 'Terry Connors'});
            console.log(stickTimes);
        });
        resolve()
    }
})
})
await requestPromise

console.log(stickTimes);
return stickTimes;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading