【问题标题】:Why isn't my Async Await flow not showing the results expected?为什么我的 Async Await 流程没有显示预期的结果?
【发布时间】: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


【解决方案1】:

绝对你会得到未定义,因为你结合了 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();

【讨论】:

    【解决方案2】:
    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      相关资源
      最近更新 更多