【发布时间】:2019-10-14 06:58:41
【问题描述】:
我在getJsonProducts 上使用异步,我在console.log(products) 之前等待,但它仍然打印未定义。我想等待,暂停直到承诺得到解决?
为什么看不到产品?
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();
我知道还有其他方法可以实现这一点,但我想了解为什么这不起作用。
【问题讨论】:
-
你需要承诺
fs.readFile才能await它。根据经验,永远不要将async function作为异步回调传递! -
是的,我想,我只是在尝试不同的东西。
标签: node.js async-await