我需要将bluebird承诺用于以下场景(已经使用顺序方法在本机承诺中实现),但是混淆了如何在bluebird中执行此操作。
data :
[
{
field1 : value1,
field2 : [
subfield1 : subvalue1,
subfield2 : subvalue2
]
field3 : value3,
},
{
field1 : value1,
field2 : [
subfield1 : subvalue1,
subfield2 : subvalue2
]
field3 : value3,
}
]
目前我尝试过类似以下的
var bbPromise = require("bluebird");
db.connect(dsn).then(prepareData).then( (results) => {
}).catch( (err) => {
console.log(err)
});
function prepareData(dbObject) {
let recordsToInsert = [];
let promises = [];
request.forEach(function(row, idx) {
let procesedRow = {
// data build from row
};
promises.push( childFunction(procesedRow));
});
bbPromise.all( promises).then( (results) => {
// resolve here ?
})
}
function childFunction(data) {
bbPromise.join(
firstFunction(data),
secondFunction(data),
thirdFunction(data),
fourthFunction(data)
)
.then( (results) => {
data.firstResults = results[0];
data.secondResults = results[1];
data.thirdResults = results[2];
data.fourthResults = results[3];
return data;
}).then( fifthFunction )
.then( (results) => {
data.fifthResults = results;
return insertData(data);
})
.then( (results) => {
bbPromise.resolve(results);
});
}
在任何实际操作之前执行但最终成功调用(请参阅此处的解决方法?)。
答案 0 :(得分:1)
要理解的导入事项是promises是 result 值。你不能忘记return
他们,否则他们会被忽略。您不需要“解决任何问题”,您需要做的只是return
承诺,它们将自动链接:
function prepareData(dbObject) {
let recordsToInsert = [];
let promises = request.map(function(row, idx) {
// ^^^
let procesedRow = {
// data build from row
};
return childFunction(procesedRow);
// ^^^^^^ (ok, `push` would've worked as well)
});
return bbPromise.all(promises);
// ^^^^^^
}
function childFunction(data) {
return bbPromise.join(
// ^^^^^^
firstFunction(data),
secondFunction(data),
thirdFunction(data),
fourthFunction(data)
).then(results => {
data.firstResults = results[0];
data.secondResults = results[1];
data.thirdResults = results[2];
data.fourthResults = results[3];
return data;
}).then(fifthFunction).then(results => {
data.fifthResults = results;
return insertData(data);
});
}