如何解决如何加速nodejs中的函数调用
一旦某些数据被发布到数据库,我就会向后端创建一个获取请求。因此,为了在触发 get 请求之前等待 post 请求完成,我实现了这样的等待逻辑,postArray.called = true
const postArray = async (arr) => {
const movie = {
name: searchTerm,result: arr
}
try {
await axios({
method: 'post',url: url,data: result,headers:{
"Content-Type":"application/json","Accept":"application/json"
}
})
} catch (error) {
console.log(error)
}
postArray.called = true
}
为了让 get 请求等待 post 请求,我使用了这样的 if 条件。
app.get("/getNewList",(req,res)=>{
if(postArray.called){
process.nextTick(()=>{
axios.get('http://localhost:3001/List')
.then(response => res.send(response.data))
.catch(error => res.send(error))
})
}
})
问题是,这个 get 请求在 post 请求被调用后的 2 或 3 分钟内没有被调用。我需要一种方法来加速这个函数调用,这样它就不会完全减慢我的应用程序的速度。
有时,请求超时,我收到超时错误。
////编辑////
我被告知使用 if(postArray.called)
与让 get 请求等待不同,所以我尝试了其他方法。
async function getData(props){
let Result = []
let fetchAgain = await axios.get('/getNewList')
Result = fetchAgain.data.find(x => x.name.toLowerCase() === props.toLowerCase()).result
showResult(Result)
}
async function fetchPost(props){
axios.post(`/${props}`)
.then((res) =>{
if(res.status === 200){
getData(props)
}
})
}
这是来自前端的新请求。我声明了一个函数来调用 get 请求,然后将它传递给 post 请求的 .then
部分。
这仍然不起作用。请记住,if(postArray.called)
已从后端的 get 请求中删除
fetchPost
函数用于将数据发送到我的后端,然后后端查询两个外部 API:
function newFetch(a){
const promises = [
Fetch(`https://externalapi1?=${a}.com`,Fetch(`https://externalapi2?=${a}.com`,]
Promise.all(promises)
.then(values =>{
const result = values.filter(o=>Object.values(o).every(v=>v) && Object.entries(o).length);
postArray(result)}
.catch(err => console.log(err))
}
这是调用 postArray 函数的地方。然后我打算从后端获取这些数据以呈现给我的客户端。使用上面列出的两种失败的方法
///结束编辑///
/////这是调用newFetch的地方////
app.post("/:endpoint([\\/\\w\\ ]*)",async (req,res) =>{
newFetchPromise = await newFetch(req.params.endpoint).catch(err => {
newFetchPromise = null
})
})
解决方法
假设这是针对每个服务器的操作,而不是针对每个用户的操作...
首先,修复 newFetch()
使其返回与 postArray()
完成时相关的承诺:
function newFetch(a) {
const promises = [
Fetch(`https://externalapi1?=${a}.com`),Fetch(`https://externalapi2?=${a}.com`),];
return Promise.all(promises).then(values => {
const result = values.filter(o => Object.values(o).every(v => v) && Object.entries(o).length);
return postArray(result);
}).catch(err => {
// log and rethrow so caller sees the error
console.log(err);
throw err;
});
}
然后,无论您在何处调用 newFetch()
,都需要将返回的 Promise 保存到模块级变量中:
// module level variable
let newFetchPromise;
// wherever you call newFetch()
newFetchPromise = newFetch(...).catch(err => {
newFetchPromise = null;
});
然后,在您的路由处理程序中,您可以等待该模块级承诺:
app.get("/getNewList",(req,res)=>{
if (newFetchPromise) {
// wait for newFetchPromise
// this will work whether newFetchPromise has already finished or is still
// processing
newFetchPromise.then(() => {
return axios.get('http://localhost:3001/List');
}).then(response => {
res.send(response.data);
}).catch(err => {
// maybe want to set an error status here?
res.send(err);
});
} else {
// have to send some sort of response here if there was no newFetchPromise
console.log("no newFetchPromise to wait for");
res.sendStatus(500);
}
});
当再次调用 newFetch()
时,它只会将模块级别的 newFetchPromise 更新为最新的,因此任何新的 /getNewList
请求将始终等待最新的 promise,而任何先前的请求将等待与他们最初等待的相同。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。