Ad

Why Isn't My Async Await Flow Not Showing The Results Expected?

- 1 answer

Im using Async on getJsonProducts, and I'm awaiting before console.log(products) but it still prints undefined. I thought await, pauses until the promise has been resolved?

Why aren't the products visible?

async function getJsonProducts(){
let products;
  await fs.readFile('./products.json','utf-8',async (err,data)=>{
    if(err)
      throw err;

    let r = /\"\_id.*\,(?=\"info\")|(?<=hex.*\})\,\"\_+v.*\d/g
    let d = await data.replace(r,'');
        d = await d.split('\n');d.pop();
        products = await d.map(s=>JSON.parse(s));
      //console.log(products) prints here
  })
  await console.log(products); //prints undefined here?
}


const seedProducts = async () => {
  await getJsonProducts();
}
seedProducts();

I know there's other ways to implement this but I want to understand why this isn't working.

Ad

Answer

absolutely you will get undefined because you combined between async-await and the callback, also this is not how async-await works, if you want to use async await , you can follow my code

async function getJsonProducts() {
 return new Promise((reoslve, reject) => {
  fs.readFile('./products.json', 'utf-8', async (err, data) => {
   if (err) reject(err)
   let r = /\"\_id.*\,(?=\"info\")|(?<=hex.*\})\,\"\_+v.*\d/g
   let d = data.replace(r, '');
   d = d.split('\n');
   d.pop();
   const products = d.map(s => JSON.parse(s));
   resolve(products)
  })
})
}
const seedProducts = async () => {
 const products = await getJsonProducts();
 conosle.log(products); // you will get products
}
seedProducts();
Ad
source: stackoverflow.com
Ad