javascript - 在 promise 中循环数组并将其作为参数传递给下一个 promise 后,如何在链接时返回一个值?

标签 javascript foreach es6-promise

我正在尝试从端点获取数据。尽管如此,除了我认为我犯了一个我不太了解这个特定结构的小错误外,一切正常。

我在 .then() 中使用 forEach() 现在我想将 forEach 的返回值传递给下一个链接的 .then() promise ,而不是在另一个 .then 中创建一个新的 .then() ()

const url = 'https://jsonplaceholder.typicode.com/users';
/*r = response, v = value, e = error, n = names array, iv = item value */

axios.get(url)
.then( r => r )
.then( r => r.data )
.then( r => r.map( v => v ) )
.then( r => {const n = r; return n} )
.then( n => { n.forEach( v => v) } )
.then( /* HERE I WANT TO IMPLEMENT THE RETURNED VALUE FROM THE PREVIOUS FOREACH() FUNCTION*/ )
.catch( e => e.respose ? console.log(e.response.status) : console.log(e.message) )

代码已更新

axios.get(url)
.then( response => response.data )

/* Creates a copy from the responded array */
.then( 
  response => {
   const new_array = response.map( value => value )
   return new_array;
  } 
)

/* 
  Gets the name property for each value inside the copied array and stores it into a new array called names_array 
 */
.then(
  new_array => {
    const names_array = [];
    new_array.forEach(
      item => names_array.push(item.name)
    )
    return names_array
  }
)
.then(
  names => {
    console.log(names.sort( (a, b) => b-a) )

  }
)

/* Error handling */
.catch( e => e.respose ? console.log(e.response.status) : console.log(e.message) )

最佳答案

如果您想要的只是来自响应对象的名称数组,那么在链中使用不必要的 then() 会使整个事情过于复杂。

创建 const new_array = response.map( value => value ) 是一个毫无意义的步骤,它只是无缘无故地复制原始数组

您只需要一个简单的 map() 即可在第一个 then() 中返回名称

const url = 'https://jsonplaceholder.typicode.com/users';

const getNames = () => axios.get(url)
  .then(res => res.data.map(o => o.name).sort((a, b) => a.localeCompare(b)))

getNames().then(sortedNames => console.log(sortedNames))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

关于javascript - 在 promise 中循环数组并将其作为参数传递给下一个 promise 后,如何在链接时返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53021843/

相关文章:

javascript - 如何使用 jquery 从查询字符串中获取两个参数值?

具有锁定属性的 c# foreach

javascript - 在 Node.js 中使用 ES6 Promise 返回空响应

php - AJAX:打开另一个div中的内容

javascript - JavaScript 的 forEach 循环如何决定跳过或迭代数组中的 "undefined"和 "null"元素?

php - 使用嵌套的 foreach 循环取消设置数组中的对象无法按预期工作?

javascript - 从一组日期中获取每周和每月数据的最佳方法是什么?

jquery - 包括带有 Spring Boot 的 ES6 和 Webpack

javascript - 我应该在调度时捕获 Redux promise 错误还是只在 reducer 中处理它?

javascript - 如何使用 !不令人困惑?