Ad
Why Isn't My Async Await Flow Not Showing The Results Expected?
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
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error
Ad