为什么我的异步等待流未显示预期的结果?
我正在getJsonProducts
上使用Async,并且我正在等待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();
我知道还有其他方法可以实现此目的,但我想了解为什么这不起作用。
回答如下:function getFile(cb) {
fs.readFile('./products.json', 'utf-8', (err, data) => {
if (err)
throw err;
let r = /\"\_id.*\,(?=\"info\")|(?<=hex.*\})\,\"\_+v.*\d/g
let d = data.replace(r, '');
d = d.split('\n');
d.pop();
cb(d.map(s => JSON.parse(s)));
})
}
async function getJsonProducts() {
this.getFile(products => console.log(products));
}
const seedProducts = async () => {
await getJsonProducts();
}
seedProducts();