为什么我的“异步等待”流没有显示预期的结果?

时间:2019-10-13 20:58:47

标签: node.js async-await

我正在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();

我知道还有其他方法可以实现此目的,但我想了解为什么它不起作用。

2 个答案:

答案 0 :(得分:0)

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();

答案 1 :(得分:0)

由于您在async-await和回调之间结合使用,所以绝对不会定义,这也不是async-await的工作方式, 如果要使用async await,可以按照我的代码

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();