【问题标题】:how i can access the variable value outside the map?我如何访问地图外的变量值?
【发布时间】:2020-07-25 11:06:57
【问题描述】:

我想用值访问地图外的变量,但地图外的值为 null 这是我的代码

let currentUser = await User.findById(req.user._id);
  let wordDetails = [];
  let findSameWord;
  let wordDetail = [];

  currentUser.learn.map(
    catchAsync(async (words) => {
       let wordDetail = await Learn.findById(words);
       wordDetails.push(wordDetail);  
       console.log(wordDetails); //here get me correct array
       return wordDetails;
     
    })
  );

  console.log(wordDetails); // here is an empty array

【问题讨论】:

  • 当你对它的返回值不感兴趣时​​,你不应该使用.map()
  • 我想如果你去掉return,你会得到正确的答案

标签: javascript arrays dictionary push


【解决方案1】:

试试看:

let currentUser = await User.findById(req.user._id);
let wordDetails = [];
let findSameWord;
let wordDetail = [];

await Promise.all(currentUser.learn.map(
    catchAsync(async (words) => {
        let wordDetail = await Learn.findById(words);
        wordDetails.push(wordDetail);
        console.log(wordDetails); //here get me correct array
        return wordDetails;

    })
));

console.log(wordDetails); // here is an empty array

【讨论】:

  • 我喜欢这个,但不幸的是没有像我预期的那样工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多