最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

为什么我的异步等待流未显示预期的结果?

运维笔记admin12浏览0评论

为什么我的异步等待流未显示预期的结果?

为什么我的异步等待流未显示预期的结果?

我正在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();
发布评论

评论列表(0)

  1. 暂无评论