2

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;
},
15
  • 1
    You'd need to provided the semantics of airtableQuery.getTable() for anyone to be able to write a decent answer. Commented Jun 11, 2020 at 1:12
  • 1
    The reason you often see setTimeout in questions about promises is because it's a simple way to create something that runs asynchronously. Most async functions involve external servers. Commented Jun 11, 2020 at 1:21
  • 2
    @RobbyCornelissen - what is the purpose of downvoting every single answer if we are just trying to give solutions, given limited information. Async/await would work just fine if getTable() was an actual Promise as it could be indicated from the initial question. Commented Jun 11, 2020 at 1:21
  • 1
    @RobbyCornelissen in most cases that would work right away. I do not see the reason for being so negative. You can always edit the answer given additional information in the comment section under the answer until you get it right. Commented Jun 11, 2020 at 1:24
  • 1
    @RobbyCornelissen Correct, that is my bad. For that reason, I edited it right away. My apologies. Commented Jun 11, 2020 at 1:31

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I tried that actually and when I console.log(allResults.length); it still says zero length.
I appreciate it. I hope I did not cause you too much nerve. My apologies again - thanks for giving me the benefit of the doubt.
Ah don't worry about me. I'm 10,000% not worth it :P Good that we could work together and get to an accepted answer for this question.
Haha :P You are good, man. Yes, we got that right in the end, phew...
0

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

2 Comments

I think you're close. Probably only need to resolve the promise on done. @KirkRoss what API is eachPage() part of? Does it take 3 callbacks (data, error, done)?
@RobbyCornelissen I'm not sure. eachPage() is part of the airtable.js library. IN the end, Jakub's answer ended up working, but thank you kindly for your thoughtful responses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.