Javascript 使用承诺时的许可代码
我对Nodejs和异步编程都是新手,所以我正在尝试制作一个购物项目,我只想澄清一下,尽管我的程序工作得很好,但我的方法正确与否 控制器文件Javascript 使用承诺时的许可代码,javascript,node.js,Javascript,Node.js,我对Nodejs和异步编程都是新手,所以我正在尝试制作一个购物项目,我只想澄清一下,尽管我的程序工作得很好,但我的方法正确与否 控制器文件 exports.posteditproduct = (req, res, next) => { const upprodid = req.body.productid; const upprodtitle = req.body.title; const upprodprice = req.body.price; const upprod
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('/')
}
模型
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)
})
})
}
那么,如果在我的模型文件中我做了所有的事情,然后在resolve()中返回最后一个变量,然后在我刚刚使用的控制器文件中返回,可以吗
.then(function(value) {
//and then write in file here
})
如果我有一个包含n个条目的非常大的文件,这种方法可以吗?
或者我应该在updateproduct方法中的Promise中也编写writeFile方法吗?Hi,也许在异步函数中执行I/O操作?您可以对难以阅读的代码进行格式化吗?@Xesenix现在可以了吗?@jspcal这真的很重要吗?我是说在使用Promission时有什么问题吗?所以我想了一下,对于非常大的文件,您必须使用,如果您想知道其中的部分代码是否以异步方式完成,那么答案是肯定的,但这并不意味着单独的进程正在处理它,javascript中的异步仍然在一个进程上完成,并且只能完成一件事情同时完成。您可能需要研究Hi,或者在异步函数中执行I/O?您可以处理代码格式设置吗?很难阅读?@Xesenix现在可以了吗?@jspcal这真的很重要吗?我是说在使用Promission时有什么问题吗?所以我想了一下,对于非常大的文件,您必须使用,如果您想知道其中的部分代码是否以异步方式完成,那么答案是肯定的,但这并不意味着单独的进程正在处理它,javascript中的异步仍然在一个进程上完成,并且只能完成一件事情同时完成。你可能想研究一下