【发布时间】:2017-12-20 16:24:06
【问题描述】:
我一直在为 Promises 苦苦挣扎,想知道 Promises 是如何工作的。 在我的项目中,我使用 Bookshelfjs ORM 从 Postgres 中获取数据。
这是我现在正在处理的代码。我在此请求中获得了一组设备 ID,并且每个设备都以两种模式之一运行。
router.post('/devices', function (req, res, next) {
var currentData = [];
var deviceIds = req.body.devices;
loadash.forEach(deviceIds, function (device) {
var deviceid = device.deviceid;
Device.forge()
.where({deviceid: deviceid})
.fetch({columns: ['id', 'mode']})
.then(function (fetchedDevice) {
if(fetchedDevice.get('mode') === 1) {
Model_1.forge()
.where({device_id: fetchedDevice.get('id')})
.orderBy('epoch_time', 'DESC')
.fetch()
.then(function (modelOne) {
//first push
currentData.push(modelOne.toJSON());
//array with first push data
console.log(currentData)
})
.catch(function (err) {
console.log(err);
});
}
else if(fetchedDevice.get('mode') === 2) {
Model_2.forge()
.where({device_id: fetchedDevice.get('id')})
.orderBy('epoch_time', 'DESC')
.fetch()
.then(function (modelTwo) {
//second push
currentData.push(modelTwo.toJSON());
//array not empty here(shows data from both push)
console.log(currentData);
})
.catch(function (err) {
console.log(err);
});
}
})
.catch(function (err) {
console.log(err);
});
});
//This shows an empty array
console.log('Final: ' +currentData);
});
现在,我知道这是由于 Javascript 的异步特性而发生的。我的问题是
在所有
push()都已执行后,如何显示最终数组?我尝试使用Promise.all()方法执行此操作,但没有成功。是否可以从每个 promise 中返回
modelOne或modelTwo然后推送到数组?我怎样才能做到这一点?
【问题讨论】:
-
1.您将需要类似 Promise.all(arrayOfThings.map(() => (//return a promise))).then((results//结果数组) => (_.forEach(...))) ; 2. 你可以通过resolve从promise中返回一个对象。您可以通过 resolve({modelOne: ... , modelTwo: ...}) 返回,然后通过 then((result) => { use it }); 在 then 函数中使用它们
-
@TyanHauChiau 正如我所说,我尝试了
Promise.all(),但我只从Device.forge()承诺中获得了价值。也许我做错了,或者把它放在了错误的位置。您能否解释一下如何使用Promise.all()正确实现这一目标? -
你的代码看起来像这样吗:假设你为一个名为 deviceFunc() 的设备包装了所有异步函数 { return new Promise((resolve, reject) => (if (model1) resolve(model1 ) 否则解决(model1))) }。并且您想获得所有设备的数组。你做 Promise.all(devices.map((device, index) => (deciveFunc(device))))
标签: javascript postgresql express promise bookshelf.js