异步/等待对象未分配

时间:2019-03-14 22:40:19

标签: javascript node.js mongoose properties

我有一个异步/等待功能,它没有分配给对象,我也不知道为什么。我正在安慰结果,它看起来像犹太洁食,但是当它碰到对象的实际分配时,它没有分配。我将在下面解释:

下面是代码:

这只是asyncForEach的帮助函数:

  async function asyncForEach(array, callback) {
    for (let index = 0; index < array.length; index++) {
      await callback(array[index], index, array);
    }
  }

然后我有以下内容:

const asyncFunc = async () => {
  await asyncForEach(tempPosts, async (tempPost) => {
    if (tempPost.fileName!=''){

      console.log('tempPosts[tempPosts.indexOf(tempPost)]: ',
      tempPosts[tempPosts.indexOf(tempPost)])

      console.log("await fsPromise.readFile(__dirname+'/../picFolder/sharp/'+tempPost.fileName)", 
      await fsPromise.readFile(__dirname+'/../picFolder/sharp                
      /'+tempPost.fileName))

      tempPosts[tempPosts.indexOf(tempPost)]['data'] = 
      await fsPromise.readFile(__dirname+'/../picFolder/sharp/'+tempPost.fileName)

      console.log('after assignment and value of tempPosts in asyncForEach: ', tempPosts)
    }
  })
}

这是三个javascript日志的结果:

console.log('tempPosts[tempPosts.indexOf(tempPost)]: ',
tempPosts[tempPosts.indexOf(tempPost)])

结果

tempPosts[tempPosts.indexOf(tempPost)]:  { flags: 0,
  fileName: '1552601360288&&travelmodal.png',
  comments: [],
  _id: 5c8ad110ef45f6e51a323a18,
  body: 'asdasdfasdf',
  created: 2019-03-14T22:09:20.427Z,
  __v: 0 }

这似乎是正确的。

console.log("await fsPromise.readFile(__dirname+'/../picFolder/sharp/'+tempPost.fileName)", 
await fsPromise.readFile(__dirname+'/../picFolder/sharp                
  /'+tempPost.fileName))

给......

await fsPromise.readFile(__dirname+'/../picFolder/sharp/'+tempPost.fileName)
<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 c8 00 00 00 62 08 06 00 00 00 15 df 9c 16 00 00 00 09 70 48 59 73 00 00 16 25 00 00 16 25 01 ... >

这是我想要的真正长的数据缓冲区字符串。很好。

如何

after assignment and value of tempPosts in asyncForEach:  [ { flags: 0,
    fileName: '1552601360288&&travelmodal.png',
    comments: [],
    _id: 5c8ad110ef45f6e51a323a18,
    body: 'asdasdfasdf',
    created: 2019-03-14T22:09:20.427Z,
    __v: 0 },
  { flags: 0,
    fileName: '1552601320137&&Screen Shot 2019-03-09 at 10.03.09 AM.png',
    comments: [],
    _id: 5c8ad0e8ef45f6e51a323a17,
    body: 'adf',
    created: 2019-03-14T22:08:40.336Z,
    __v: 0 } ]

什么?我的电话是Object['newKey'] = await fsPromise.readFile(yadayada),其中await fsPromise.readFile(yadayada)在console.log中显示正常工作。为什么我不能这样做,这毫无意义。

1 个答案:

答案 0 :(得分:1)

我刚刚进行了一次小测试,如果您尝试获取要打印的'data'属性,则似乎应该可以看到输出:

console.log('after assignment and value of tempPost in asyncForEach: ',tempPosts[tempPosts.indexOf(tempPost)]['data'])

但是尝试进行console.log(tempPost)将不会显示data,除非您已在TempPost的猫鼬模式中定义了该键

如果您想将tempPost作为纯JavaScript对象处理,则需要通过调用toObject将tempPost模型文档转换为纯JavaScript对象,例如。 tempPost = tempPost.toObject();之后,您的console.log('after assignment and value of tempPosts in asyncForEach: ', tempPosts)将给出预期的结果。

所以这与异步/等待和赋值(imo)毫无关系