Home > front end >  JS await is not waiting for the request to finish
JS await is not waiting for the request to finish

Time:08-02

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.

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?

CodePudding user response:

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;
}

CodePudding user response:

@neon, async await are used on top of Promises as synthetic sugar only. So whenever you wants to use it, it should be on top of Promise function. Here function that you have declared (request) is not a Promise. You can simply create Promise using new keyword and passing resolve and request as executor function to it. Within it, you can pass your current function and return values out of it. Hope it will help.

  • Related