Object.assign在Nodejs中

时间:2018-02-02 15:40:47

标签: javascript node.js

我在邮件中做foreach并获取用户信息。

messages.map(function (message, index) { 
  obj[index] = { 
    id: message._id, 
    createdAt: message.createdAt, 
    text: message.text, 
    img: message.img
  };

  User.findById(message.userId).then((user)=>{ 
  Object.assign(obj[index], {user_id: user._id}, {username: user.username}, {image_photo : user.userId});
}).catch((error)=>{  
 console.log(error); 
}); 

Object.assign async无法正常工作,问题是RewriteEngine On RewriteRule ^this-url$ http://www.anotherdomain.com/ [NC,L,R=301] # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress

1 个答案:

答案 0 :(得分:1)

您没有维护您的承诺链,因此您不会等待任何承诺。由于您还没有等到Promise完成,因此当您的代码超出此上下文时,通过您的obj[index]Object.assign()的合并还没有发生。

要解决此问题,您需要等待整个Promise链完成工作。首先将承诺从user.findById()返回到messages.map()。由于map()返回一个新的值数组,在本例中为Promises,我们可以将该数组传递给Promise.all()

Promise.all(),将等待给定数组中的所有Promise在调用通过.then()注册的回调之前完成解析,或者可以return返回到另一个具有自己的Promise的函数链。

// This code assumes let obj = {} is present within scope
let userPromises = messages.map((message, index) => { 
  obj[index] = { 
    id: message._id, 
    createdAt: message.createdAt, 
    text: message.text, 
    img: message.img
  }

  // return the Promise from User.findById()
  return User.findById(message.userId)
    .then(user => ( 
      // Merge obj[index] with user
      Object.assign(obj[index], {user_id: user._id, username: user.username, image_photo : user.userId})
    ))
    .catch(error => console.log(error))
}) 

// return your Promise chain and await all your promises then take an action
return Promise.all(userPromises)
  .then(() => {
    // Will print fully filled with user info
    console.log(JSON.stringify(obj))
  })

也可以使用async/await

编写
let userPromises = messages.map(async (message, index) => { 
  obj[index] = { 
    id: message._id, 
    createdAt: message.createdAt, 
    text: message.text, 
    img: message.img
  }

  try {    
    // This is equivalent to User.findById(message.userId).then(user => {...})
    let user = await User.findById(message.userId)

    // Merge obj[index] with user
    Object.assign(obj[index], {user_id: user._id, username: user.username, image_photo : user.userId})
  } catch (err) {
    console.log(JSON.stringify(obj))
  }
})

return Promise.all(userPromises)
  .then(() => console.log(JSON.stringify(obj)))