使用Promises时的间隙代码

时间:2019-06-21 22:45:25

标签: javascript node.js

我是Nodejs和异步编程的新手,所以我试图做一个购物项目,我只是想澄清一下,即使我的程序运行良好,但我的方法正确与否

控制器文件

<form 
  [formGroup]="form"
  (submit)="onFormSubmit()">
  <div 
    formArrayName="data"
    *ngFor="let item of form.controls['data'].controls; let i = index;"
    >
    <div [formGroupName]="i">
      <input type="text" formControlName="name">
      <input type="text" formControlName="quantity">
      <button type="button" (click)="removeItem(i)">Remove</button>
    </div>
    <br>
  </div>
  <button type="button" (click)="addItem()">Add new Item</button>
  <button type="submit">Submit</button>
</form>

<hr>

<h2>Form Data</h2>

<pre>{{ form.value | json }}</pre>

<h2>Data</h2>
<p>This will only reflect after Submit</p>
<pre>{{ data | json }}</pre>

模型

exports.posteditproduct = (req, res, next) => {
  const upprodid = req.body.productid;
  const upprodtitle = req.body.title;
  const upprodprice = req.body.price;
  const upprodimg = req.body.imageurl;
  const upproddesc = req.body.description;
  Product(
    upprodid,
    upprodtitle,
    upprodimg,
    upprodprice,
    upproddesc
  );

  Product.updateproduct(
    upprodid,
    upprodtitle,
    upprodprice,
    upprodimg,
    upproddesc
  ).then(function(value){
    console.log(value)
    fs.writeFile(p,JSON.stringify(value),err=>{
      console.log(err)
    })
  })
  res.redirect('/')
}

如果在模型文件中我做了所有的工作,然后在resolve()中返回最终变量,然后在控制器文件中我仅使用

static updateproduct(
  upprodid,
  upprodtitle,
  upprodprice,
  upprodimg,
  upproddesc
) {
  const p = path.join(
    path.dirname(process.mainModule.filename),
    'data',
    'products.json'
  )

  return new Promise((resolve, reject) => {
    fs.readFile(p, (err, data) => {
      const allproducts = JSON.parse(data)
      const existproductid = allproducts.findIndex(prod => prod.id === upprodid)
      const upproduct = [...allproducts]
      const spreadall = upproduct[existproductid]

      spreadall.id = upprodid
      spreadall.title = upprodtitle
      spreadall.imageurl = upprodimg
      spreadall.price = upprodprice
      spreadall.description = upproddesc
      upproduct[existproductid] = spreadall

      return resolve(upproduct)
    })
  })
}

如果我的文件非常大且n号为n,这种方法是否可以?的条目? 还是应该在updateproduct方法的Promise中也写writeFile方法?

0 个答案:

没有答案