Kirk Ross
Kirk Ross

Reputation: 7163

JavaScript - replace setTimeout with async / await

First, I know this is a common question. I'm trying to get a handle on how to use async / await in place of setTimeouts, but all the examples I see online use a setTimeout to simulate the async. This throws me off when it's a set timeout that I'm trying to replace.

In the function below, I want this.filteredResultsto await the results of an API call before trying to filter those results and assign it to this.filteredResults.

getResults() {
  let allResults= airtableQuery.getTable("Transfers"); // API call using imported 'getTable' function

  console.log(allResults); // returns full array ▶[] although it's not available for filtering yet.

  setTimeout(() => { // I want to replace this timeout
    this.filteredResults = allResults.filter(
      (result) => result.fields.User === "dev"
    );
  }, 250); // random ms that is roughly how long airtableQuery takes for the API call.
},

And the airtableQuery:

getTable(table) {
  let recordsArr = [];
  base(`${table}`)
    .select({
      maxRecords: 8000,
    })
    .eachPage(
      function page(records, fetchNextPage) {
        records.forEach((record) => {
          recordsArr.push(record);
        });
        fetchNextPage();
      },
      function done(err) {
        if (err) {
          this.$toasted.error(err);
        }
      }
    );
  return recordsArr;
},

Upvotes: 2

Views: 1838

Answers (2)

Jakub A Suplicki
Jakub A Suplicki

Reputation: 4801

Please make the outer function an async function and then await the results before filtering them.

async function getResults() {
      let allResults = await airtableQuery.getTable("Transfers");
       this.filteredResults = allResults.filter(
         (result) => result.fields.User === "dev"
       );
},

Given that getTable() is not a Promise, await will not do anything. For that reason, we can make getTable() return a Promise which will resolve with recordsArr.

getTable(table) {
    return new Promise((resolve, reject) => {
        let recordsArr = [];
        base(`${table}`)
            .select({
                maxRecords: 8000,
            })
            .eachPage(
                function page(records, fetchNextPage) {
                    records.forEach((record) => {
                        recordsArr.push(record);
                    });
                    fetchNextPage();

                },
                function done(err) {
                    if (err) {
                        this.$toasted.error(err);
                        reject(err)
                    }else {
                        resolve(recordsArr)
                    }
                }
            );
    })
}

Hope it helps.

Upvotes: 3

Joinwang
Joinwang

Reputation: 110

i always likes primise,this my code show you

getTable(table) {
    return new Promise((res, rej) => {
        let recordsArr = [];
        base(`${table}`)
            .select({
                maxRecords: 8000,
            })
            .eachPage(
                function page(records, fetchNextPage) {
                    records.forEach((record) => {
                        recordsArr.push(record);
                    });
                    fetchNextPage();
                    res(recordsArr)
                },
                function done(err) {
                    if (err) {
                        this.$toasted.error(err);
                        rej(err)
                    }
                }
            );
    })
}
getResults() {
  airtableQuery.getTable("Transfers").then(res => {
    let allResults = res
    console.log(allResults);
    this.filteredResults = allResults.filter(
      (result) => result.fields.User === "dev"
    );
  }); 
}

Upvotes: 0

Related Questions