Promise / async-await with mongoose,返回空数组

时间:2017-05-21 07:39:30

标签: javascript node.js mongoose promise async-await

最后的控制台返回空数组。 控制台在ids.map函数完成之前运行

---
- hosts: local
  remote_user: ansible
  gather_facts: no
  become: yes
  become_method: sudo

  vars:
    username: myuser

  tasks:

    - name: get user info
      getent:
        split: ":"
        database: passwd
        key: "{{ username }}"

    - name: Get authorized_keys
      shell: cat "{{ getent_passwd[username][4]  }}"/.ssh/authorized_keys
      register: read_key

    - name: Prints out authorized_key
      debug: var=read_key.stdout_lines

我做错了什么?

2 个答案:

答案 0 :(得分:5)

不等待.map代码,因此console.log会在映射发生之前发生。

如果您想等待地图,可以Promise.all使用await

var ids = [];
var allLync = []
var user = await User.findOne(args.user)
ids.push(user._id)
user.following.map(x => {
    ids.push(x)
})
// note the await
await Promise.all(ids.map(async x => {
    var lync = await Lync.find({ "author": x })
    lync.map(u => {
        allLync.push(u); // you had a typo there
    })
}));

console.log(allLync)

请注意,由于您使用.map,因此可以显着缩短代码:

const user = await User.findOne(args.user)
const ids = users.following.concat(user._id);
const allLync = await Promise.all(ids.map(id => Lync.find({"author": x })));
console.log(allLync); 

答案 1 :(得分:0)

Promise.map()现在是一个选项,如果您不介意使用bluebird的话,它会更简洁一些。 看起来可能像这样:

const user = await User.findOne(args.user);
const ids = users.following.concat(user._id);
const allLync = await Promise.map(ids, (id => Lync.find({"author": x })));
console.log(allLync); 

http://bluebirdjs.com/docs/api/promise.map.html。我真的很喜欢使用它。