我有一个包含值列表的数组,其中一些是需要解析的promise。
allGlobalFilters": [
{
"id": 503,
"pubId": 18,
"type": 15,
"value": "{ \"adsize\": [\"638x335\" , \"400x300\" , \"300x1050\", \"320x100\", \"640x480\" , \"700x392\", \"360x480\", \"896x502\", \"960x538\", \"1024x573\", \"1088x609\"]}",
"status": 4,
"createTs": null,
"updateTs": null,
"createUser": "MMM",
"updateUser": null,
"percentage": 100,
"rtbSspPublishers": { // the promise part
"id": 18,
"name": "Mobile Nations\r\n",
"domain": "http://www.mobilenations.com",
"extPublisherId": 17
}
},
{
"id": 505,
"pubId": 19,
"type": 15,
"value": "{ \"adPlatformType\": [\"APP\"] }",
"status": 4,
"createTs": null,
"updateTs": null,
"createUser": null,
"updateUser": null,
"percentage": 0,
"rtbSspPublishers": { // the promise part
"id": 19,
"name": "Tom's Guide",
"domain": "www.tomsguide.com",
"extPublisherId": 17
}
},
{
"id": 514,
"pubId": 19,
"type": 15,
"value": "{ \"adPlatformType\": [\"WEB\"] }",
"status": 4,
"createTs": null,
"updateTs": null,
"createUser": null,
"updateUser": null,
"percentage": 100,
"rtbSspPublishers": { // the promise part
"id": 19,
"name": "Tom's Guide",
"domain": "www.tomsguide.com",
"extPublisherId": 17
}
},
{
"id": 516,
"pubId": 19,
"type": 15,
"value": "{\"adPlatformType\": [\"MOBILE_WEB\"]}",
"status": 4,
"createTs": null,
"updateTs": null,
"createUser": null,
"updateUser": null,
"percentage": 100,
"rtbSspPublishers": { // the promise part
"id": 19,
"name": "Tom's Guide",
"domain": "www.tomsguide.com",
"extPublisherId": 17
}
}
]
现在我需要在承诺的条件下过滤这个数组,我该怎么做。
这就是我的尝试。
data.filter(d => d.rtbSspPublishers.get().then(res => res.name.includes('Mobile')));
但这似乎不起作用。如何获取异步值以使用数组过滤器?
答案 0 :(得分:0)
只需将promises映射到promise all中的数组,等待它们解析,然后将它们映射回一个新数组。你可以覆盖旧数组或只是保持对新数组的引用。
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
无对象传播的更新
let allGlobalFilters = [{
"id": 503,
"pubId": 18,
"type": 15,
"status": 4,
"createTs": null,
"updateTs": null,
"createUser": "MMM",
"updateUser": null,
"percentage": 100,
"rtbSspPublishers": Promise.resolve({
"id": 18,
"name": "Mobile Nations",
"domain": "http://www.mobilenations.com",
"extPublisherId": 17
})
}]
Promise.all(allGlobalFilters.map(({rtbSspPublishers}) => rtbSspPublishers)).then(values => {
const theNewValues = allGlobalFilters
.map((item, i) => ({...item, rtbSspPublishers: values[i]}))
.filter(item => item.rtbSspPublishers.name.startsWith('Mobile'))
})
答案 1 :(得分:0)
更通用的答案......
使用我之前准备的简单“助手”
promiseProps = obj => {
const keys = Object.keys(obj);
return Promise.all(Object.values(obj)).then(results => Object.assign({}, ...results.map((result, index) => ({[keys[index]]: result}))));
};
你只需
Promise.all(allGlobalFilters.map(obj => promiseProps(obj)))
.then(result => result.filter(({rtbSspPublishers}) => rtbSspPublishers.name.includes('Mobile'))
.then(filteredResult => {
// filteredResult is your allGlobalFilters with promises resolved
// filtered to include only the required items
console.log(filteredResult );
});
无论承诺中有多少(第一级)属性
,这都会有效