[英]NodeJs - async function javascript
I am making an api in NodeJs and I have a function that I call through the post, but before forwarding to the precise repository I run the function getProduct (idProd, product)
, but is doing console.log ('product ->' + product.name);
我正在 NodeJs 中制作一个 api,我有一个通过帖子调用的函数,但在转发到精确存储库之前,我运行函数
getProduct (idProd, product)
,但正在执行console.log ('product ->' + product.name);
before running the getProduct (idProd, product)
function.在运行
getProduct (idProd, product)
函数之前。 I do not know how to make it wait for the other function to finish.我不知道如何让它等待其他功能完成。 I already tried adding async and await , but without success
我已经尝试添加async和await ,但没有成功
exports.postItemProduto = async function (req, res) {
try {
var idProd = req.body.produtoPrincipal;
await getProduto(idProd, produto);
console.log('produto -> '+ produto.nome);
itemService.insertItem(req, function (err) {
if (err) {
return res.status(412).send({
success: false
});
}
return res.send({
success: true,
message: 'Item registado com sucesso!'
});
})
} catch (err) {
console.log(err);
return res.status(400).send({
error: 'Erro criar item'
});
};
};
function getProduto(id, produto){
var url = 'url/api/produtos/'+id;
axios
.get(url)
.then(response => {
/* let produto = new ProductDto(); */
produto.produtoId = response.data.productId;
produto.nome = response.data.nome;
produto.descricao = response.data.descricao;
produto.material_AcabamentoID = response.data.material_AcabamentoID;
produto.restrictionId = response.data.restrictionId;
/* let restriction = new RestrictionDto();
restriction = getRestriction(jsonData[i].restrictionId); */
console.log('produto -->' + produto.nome);
}).catch(error => {
console.log(error);
});
}
exports.postItemProduto = function (req, res) {
try {
var idProd = req.body.produtoPrincipal;
console.log('id --> ' + idProd);
getProduto(idProd, function(produto) {
console.log('produto -> ' + produto.nome);
});
itemService.insertItem(req, function (err) {
if (err) {
return res.status(412).send({
success: false
});
}
return res.send({
success: true,
message: 'Item registado com sucesso!'
});
})
} catch (err) {
console.log(err);
return res.status(400).send({
error: 'Erro criar item'
});
};
};
function getProduto(id, callback) {
var url = 'url/api/produtos/' + id;
axios
.get(url)
.then(response => {
/* let produto = new ProductDto(); */
produto.produtoId = response.data.productId;
produto.nome = response.data.nome;
produto.descricao = response.data.descricao;
produto.material_AcabamentoID = response.data.material_AcabamentoID;
produto.restrictionId = response.data.restrictionId;
/* let restriction = new RestrictionDto();
restriction = getRestriction(jsonData[i].restrictionId); */
callback(produto);
}).catch(error => {
console.log(error);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.