具体场景如何使用bluebird promise

How to use bluebird promise for specific scenario

我需要在以下场景中使用 bluebird promise(已经使用顺序方法在本机 promise 中实现),但搞不清楚如何在 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);
    });
}

在任何实际操作之前执行的有效但最终成功的调用(请参阅此处的解析?)。

要理解的重要一点是承诺是 结果 值。您一定不要忘记 return 它们,否则它们将被忽略。您不需要 "resolve anything",您需要做的就是 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);
    });
}