[英]Iterating over an array and joining with Bluebird
Is there a better way to write this? 有没有更好的方法来写这个? For the most part, the code below works, but I would like to clean it up if possible. 在大多数情况下,下面的代码有效,但是我想尽可能清除它。
For reference, outputs
in the initial callback is an array of objects, containing the file path and some metadata. 作为参考,初始回调中的outputs
是一个对象数组,其中包含文件路径和一些元数据。 I would like to have access to this metadata when calling this.track.attach()
, but I'm unsure how to access it later in the promise chain. 我想在调用this.track.attach()
时访问此元数据,但是我不确定如何稍后在promise链中访问它。
var query = Track.findById('54d5059b7403dda6395bb08b').exec();
var encode = encoder.encode('/* file path */');
Promise.join(query, encode, function (track, outputs) {
this.track = track;
return Promise.map(outputs, function (output) {
return upload.create(output.path, '/jr' + path.extname(output.path));
});
}).each(function (output) {
this.track.attach(output.name, 'media');
}).then(function () {
return this.track.saveAsync();
}).catch(function (err) {
console.log(err);
}).finally(function () {
encoder.cleanup();
}).bind({});
Here's one thing you could do. 这是您可以做的一件事。 It avoids the hacky .bind()
and this.track
: 它避免了hacky .bind()
和this.track
:
var query = Track.findById('54d5059b7403dda6395bb08b').exec();
var encode = encoder.encode('/* file path */');
function createForOutput(output) {
return upload.create(output.path, '/jr' + path.extname(output.path));
}
function saveToOutputs(track, outputs) {
return Promise.map(outputs, createForOutput)
.each(function (output) {
track.attach(output.name, 'media');
return track.saveAsync();
});
}
Promise.join(query, encode, saveToOutputs)
.catch(function (err) {
console.log(err);
}).finally(function () {
encoder.cleanup();
});
This approach uses a bit deeper nesting, but I think it may be a little clearer: 这种方法使用了更深层的嵌套,但是我认为它可能会更清晰一些:
var query = Track.findById('54d5059b7403dda6395bb08b').exec();
var encode = encoder.encode('/* file path */');
function createForOutput(output) {
return upload.create(output.path, '/jr' + path.extname(output.path));
}
function saveToOutputs(track, outputs) {
return Promise.each(outputs, function (output) {
createForOutput(output).then(function () {
track.attach(output.name, 'media');
return track.saveAsync();
});
});
}
Promise.join(query, encode, saveToOutputs)
.catch(function (err) {
console.log(err);
}).finally(function () {
encoder.cleanup();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.