【发布时间】:2020-05-24 15:51:26
【问题描述】:
我正在尝试从一组对象中随机抽取 3 个对象。我的数组来自 Promise。下面是代码。
代码:
var getLocations = admin.firestore().collection('locations')
getLocations = getLocations.where('area', '==', game_area)
let locations = new Promise((resolve, reject) => {
getLocations.onSnapshot(snapshot => {
var results = []
snapshot.forEach(doc => {
let result = doc.data()
result.id = doc.id
results.push(result)
})
return resolve(results)
})
})
locations.then(() => {
// Shuffle locations array and get 3
const amountOfLocations = 3
const shuffled = locations.sort(() => 0.5 - Math.random())
// Get sub-array of first n elements after shuffled
let selectedLocations = shuffled.slice(0, amountOfLocations)
}).catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
})
这是从 Promise 返回的数组的示例。注意:我简化了这个论坛的结果。
locations=[ { name: 'Radio Coffee and Beer',
timestamp: 1580676902040,
id: '1KALzdUbf7y3ex2C' },
{ name: 'ZACH Theater',
timestamp: 1580676946375,
id: 'Lpxl8xLKCFDKxIhc' },
{ name: 'Alamo Draft House',
timestamp: 1580676636972,
id: 'b5F3Tq2y9cD4WQJq' },
{ name: 'Stevie Ray Vaughn Statue',
timestamp: 1580676764120,
id: 'bIUl4JU7kUSh6eyi' },
{ timestamp: 1580676967508,
name: 'The Long Center',
id: 'xJJOprzYDt3fWqVa' } ]
如您所见,此示例数组有 5 个对象。我想从数组中随机拉出 3 个对象。我认为我的问题来自 Promise 返回数组的方式,但我不确定。
【问题讨论】:
-
console.log(selectedLocations);这是什么结果?
-
@GangadharGandi 它是空的
-
@GangadharGandi 洗牌失败了
-
locations是这个语法中的一个承诺:locations.sort(...)。您需要从 Promise 中获取价值并通过locations.then(values => {... const shuffled = values.sort(...); ... });使用它 -
@DanielWSrimpel 我有点困惑。你是说我需要做的就是使用locations.then(() => ...使用locations.then(values => ... ?
标签: javascript arrays object promise