简体   繁体   English

使用正确的回退路由结构从 nodejs 中的异步调用传递数据的最佳实践

[英]Best practice for passing data from from a asynchronous call in nodejs with correct fallback routing structure

I have a request function that makes a call to an endpoint and gets data from it.我有一个请求函数,可以调用端点并从中获取数据。 Then i pass this data to an hbs template for rendering but due to asyncronycity the array passed to template is empty.然后我将此数据传递给 hbs 模板进行渲染,但由于异步性,传递给模板的数组为空。 What is the right way to do it.什么是正确的方法。 Please help.请帮忙。 The code snippet is below.代码片段如下。

app.get("/verifier", keycloak.protect('verifier'), (req, res) => {  
  cirRes = cirJSON.parse(cirJSON.stringify(res))
  //the req object is a circular object so you cannot convert it to json normaly wihtout data loss.
  allUser = []
  access_token = cirRes.req.kauth.grant.access_token.token
  var options = { method: 'GET',
  url: 'http://localhost:8080/auth/admin/realms/create_user_realm/users',
  headers: 
   { 
     'Content-Type': 'application/x-www-form-urlencoded',
     Host: 'localhost:8080',
     Accept: '*/*',
     Authorization: `Bearer ${ access_token }` } }
  request(options, function (error, response, body) {
    if (error) throw new Error(error);
      data = JSON.parse(body)
      for (user in data){
       allUser.push(data[user])
      } 
      //console.log(allUser)
  })
  if (res.statusCode != 200) {
    res.redirect('/logout')
  }
  console.log(allUser)
  res.render('verifier', {"users": allUser})
})

The allUser comes out to be an empty array in above code. allUser 在上面的代码中是一个空数组。

edit >>>>编辑 >>>>

This question was closed given the answer in this thread.鉴于此线程中的答案,此问题已关闭。 How do I return the response from an asynchronous call? 如何从异步调用返回响应? It covers different ways to make asynchronous requests.它涵盖了发出异步请求的不同方法。

Going through the same i made this change in code经历了同样的事情,我在代码中做了这个改变

app.get("/verifier", keycloak.protect('verifier'), (req, res) => {  
  cirRes = cirJSON.parse(cirJSON.stringify(res))
  //the req object is a circular object so you cannot convert it to json normaly wihtout data loss.
  //console.log(cirRes.req.kauth.grant.access_token.token)
  allUser = []
  access_token = cirRes.req.kauth.grant.access_token.token
  var options = { method: 'GET',
  url: 'http://localhost:8080/auth/admin/realms/create_user_realm/users',
  headers: 
   { 
     'Content-Type': 'application/x-www-form-urlencoded',
     Host: 'localhost:8080',
     Accept: '*/*',
     Authorization: `Bearer ${ access_token }` } }
  request(options, function (error, response, body) {
    if (error) { throw new Error(error) }
      data = JSON.parse(body)
      for (user in data){
       allUser.push(data[user])
      } 
      //console.log(allUser)
      res.render('verifier', {"users": allUser})
    })
  if (res.statusCode != 200) {
    res.redirect('/logout')
  }
})

This works fine, but is the correct according to best practices of nodeJS and what is the best practice for this in nodeJS so that some fallback mechanism is there to render even if an error occurs in call.这工作正常,但根据 nodeJS 的最佳实践是正确的,nodeJS 中的最佳实践是什么,以便即使调用中发生错误,也有一些回退机制可以呈现。

Move your res.render() and res.redirect() calls so they are inside the callback function of your request() call.移动res.render()res.redirect()调用,使它们位于request()调用的回调函数内。 That's how you use asynchronously provided information in express when you want to send it to a user's browser or API client.这就是当你想将它发送到用户的浏览器或 API 客户端时,你如何在 express 中使用异步提供的信息。

It's perfect.这是完美的。 you need to add option variable in try-catch block.您需要在 try-catch 块中添加选项变量。

try{
var options = { method: 'GET',
  url: 'http://localhost:8080/auth/admin/realms/create_user_realm/users',
  headers: 
   { 
     'Content-Type': 'application/x-www-form-urlencoded',
     Host: 'localhost:8080',
     Accept: '*/*',
     Authorization: `Bearer ${ access_token }` } }
  request(options, function (error, response, body) {
    if (error) { throw new Error(error) }
      data = JSON.parse(body)
      for (user in data){
       allUser.push(data[user])
      } 
      //console.log(allUser)
      res.render('verifier', {"users": allUser})
    })
  if (res.statusCode != 200) {
    res.redirect('/logout')
  }

}catch(e){
  throw(e);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从异步回调NodeJS调用“父函数”的正确方法是什么 - What is the correct way to call “parent function” from asynchronous callback, NodeJS NodeJS Express API 调用结构异步事件 - NodeJS Express API call structure asynchronous events 在原始数组的条件下创建具有不同数据结构的新数组的最佳实践是什么? - What is the best practice to create a new array with different data structure on condition from the origin array? 将数据从一个 Vue.js 组件传递到 Laravel 中的另一个组件的最佳实践 - best practice for passing data from one Vue.js component to another in Laravel 从数组动态分配对象-最佳实践-Node.js JavaScript - Assigning objects dynamically from array - best practice - nodejs javascript React Routing Menu - 数据处理最佳实践 - React Routing Menu - data handling best practice 需要来自异步API调用的数据的构造函数? - Constructor that needs data from asynchronous API call? 将数据从异步调用存储到AngularJS中的变量 - Store data from asynchronous call to a variable in AngularJS 将变量从一个HTML页面传递到另一个HTML页面的最佳做法是什么? - What is the best practice for passing variables from one HTML page to another? firestore 数据结构的最佳实践是什么? - What is the best practice of firestore data structure?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM