0

I have below code in which i want to call an await after getting response in .then.

const info = new getInfo(this.fetchDetails);
info
  .retrieve()
  .then((res) => {
    const details = this.getLatestInfo(res, 'John');
  })
  .catch((error) => {
    console.log(error);
  });

In nutshell want to make const details = this.getAgentInfo(res, 'John'); as const details = await this.getLatestInfo(res, 'John'); but its giving error as "await is only valid in async function", how to make this async?

Lara
  • 2,821
  • 7
  • 39
  • 72
  • 3
    But `details` is not used anywhere or returned. Why do you need to `await` it? – VLAZ Jan 07 '21 at 16:54
  • How would you usually make a function async? Have you looked up "async" in a JS reference like the one on MDN? – Quentin Jan 07 '21 at 16:55
  • 1
    Did you try `.then(res => this.getLatestInfo(res, 'John')).then(details => { /* your code here */ })` – Wyck Jan 07 '21 at 16:57
  • @VLAZ How to return it properly? – Lara Jan 07 '21 at 16:57
  • Does this answer your question? [js - How to call an async function within a Promise .then()](https://stackoverflow.com/questions/54901478/js-how-to-call-an-async-function-within-a-promise-then) – Zachary Delano Jan 07 '21 at 16:58
  • 1
    @Lara return it where? From the promise chain? – VLAZ Jan 07 '21 at 16:58

2 Answers2

2

Mixing then() and its syntactic variant async / await is like speaking with two different accents. Rewriting the code to strictly use each variation, we get:

  1. Older way:

     function promiseReturningFunction() {
       const info = new getInfo(this.fetchDetails);
       return info.retrieve().then((res) => {
         return this.getLatestInfo(res, 'John');
       }).catch((error) => {
         console.log(error);
       });
     }
    
     // call it
     promiseReturningFunction().then(res => {
       // res will be the result of getLatestInfo()
     }
    
  2. Newer way:

     async function promiseReturningFunction() {
       const info = new getInfo(this.fetchDetails);
       try {
         const res = await info.retrieve();
         const info = await this.getLatestInfo(res, 'John');
         return info;
       } catch (error) {
         console.error(error);
       }
     }
    
     // call it
     const res = await promiseReturningFunction(); // res will be the result of getLatestInfo()
    
danh
  • 62,181
  • 10
  • 95
  • 136
-1

You need to use async keyword to make the function async as shown below.

const info = new getInfo(this.fetchDetails);
info
  .retrieve()
  .then(async (res) => {
    const details = await this.getLatestInfo(res, 'John');
  })
  .catch((error) => {
    console.log(error);
  });
Mohit Gupta
  • 109
  • 1
  • 1
  • 11