我正在尝试对数据进行扁平化和非规范化。我不明白如何使用 promise 来实现这一点。我错过了什么?

我得到的结果是:

Bob,Nancy 
Bob,Nancy 

但我想得到:

Bob,Sue 
Bob,Nancy 

代码:

var Promise = require('bluebird'); 
 
var jsonData = { 
  "Parents": [{ 
    "Name": "Bob", 
    "AllChildren": [{ 
      "Name": "Sue" 
    }, { 
      "Name": "Nancy" 
    }] 
  }, { 
    "Name": "Ron", 
    "AllChildren": [{ 
      "Name": "Betty" 
    }, { 
      "Name": "Paula" 
    }] 
  }, { 
    "Name": "Peter", 
    "AllChildren": [{ 
      "Name": "Mary" 
    }, { 
      "Name": "Sally" 
    }] 
  }] 
}; 
 
 
var promises = Promise.map(jsonData.Parents, function(parent) { 
  var record = {}; 
  record.ParentName = parent.Name; 
  var allRecords = Promise.map(parent.AllChildren, function(child) { 
    var fullRecord = record; 
    fullRecord.ChildName = child.Name; 
    return fullRecord; 
  }); 
  return Promise.all(allRecords); 
}); 
 
console.log(JSON.stringify(promises, null, 2)); 

请您参考如下方法:

这里你缺少的是, promise 是“ promise 的值”,一旦你“然后”它们就会被评估。 Promise 链中返回的值/Promise 会遍历它并由下一个 then 处理程序获取。

更新:在展平中使用 concat

像这样更改您的实现:

return Promise.map(jsonData.Parents, function(parent) { 
  return Promise.map(parent.AllChildren, function(child) { 
    return { ParentName: parent.Name, ChildName: child.Name }; 
  }); 
}) 
.reduce(function (accumulator, item){ 
  // Flatten the inner arrays 
  return accumulator.concat(item); 
}, []) 
.then(function (flattened) { 
  console.log(JSON.stringify(flattened, null, 2)); 
}); 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!