Node.js 为什么不是';我的异步等待流没有显示预期的结果吗?

Node.js 为什么不是';我的异步等待流没有显示预期的结果吗?,node.js,async-await,Node.js,Async Await,我在getJsonProducts上使用Async,我在console.log(products)之前等待,但它仍然打印未定义的内容。我想等待,暂停直到承诺得到解决 为什么产品不可见 异步函数getJsonProducts(){ 让产品; 等待fs.readFile('./products.json',utf-8',异步(错误,数据)=>{ 如果(错误) 犯错误; 设r=/\“\ \ \”id.*\,(?=\”info\”)\(?函数getFile(cb){ fs.readFile('./pro

我在
getJsonProducts
上使用Async,我在
console.log(products)
之前等待,但它仍然打印未定义的内容。我想等待,暂停直到承诺得到解决

为什么产品不可见

异步函数getJsonProducts(){ 让产品; 等待fs.readFile('./products.json',utf-8',异步(错误,数据)=>{ 如果(错误) 犯错误; 设r=/\“\ \ \”id.*\,(?=\”info\”)\(?
函数getFile(cb){
fs.readFile('./products.json',utf-8',(err,data)=>{
如果(错误)
犯错误;

让r=/\“\\\\\\\\\\\\\\\”)\\\(?由于在异步等待和回调之间进行了组合,所以绝对会得到未定义,而且异步等待也不是这样工作的, 如果您想使用AsyncWait,可以按照我的代码进行操作

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();
异步函数getJsonProducts(){ 返回新承诺((重新选择、拒绝)=>{ fs.readFile('./products.json',utf-8',async(err,data)=>{ 如果(错误)拒绝(错误)
让r=/\“\\\\\\\\\\\\\\\\\*”,(?=“info\”))(你需要承诺
fs.readFile
才能
等待它。根据经验,永远不要将
异步函数
作为异步回调传递!是的,我想,我只是在尝试不同的事情。
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();