Как я могу убедиться, что мой цикл завершается со всеми функциями, завершившимися? - PullRequest
0 голосов
/ 02 ноября 2018

Я использую nodejs.

let request = API2.sendRequest(bookId); - попытка вызова внешнего вызова API отдыха.

  1. В точке C, как мне убедиться, что все элементы в списке запущены, включая точки A и B?
  2. Как мне убедиться, что B работает после A?

Я пытался if (i === updateList.length) {, но это вернуло меня частично

Логи:

2018-11-02T16:51:33.672 Success: 5 record(s). Fail: 0 record(s). Total 10 record(s).

Коды:

'use strict';

//imports
const format = require('string-format');

let Converter = require('../common/converter');
let converter = new Converter();

const bookDao = require('../dao/bookDao.js');
const shelfDao = require('../dao/shelfDao.js');
const libDao = require('../dao/libDao.js');

const API2 = require('../common/API2.js');
const constant = require('../common/constant.js');

const security = require('../common/security.js');

function updateInfo() {

    let updateCountParams = [];
    let updateParams = [];

    let updateList = null;

    bookDao.getUpdateCount(updateCountParams, function (results) {

        if (results[0].RECCOUNT > 0) {

            bookDao.getUpdate(updateParams, function (results) {

                updateList = results;

                let removalList = [];
                let failureList = [];

                for (var i = 0; i < updateList.length; i++) {
                    let bookId = updateList[i].BOOKID;

                    let updateParam1 = [];
                    let updateParam2 = [];

                    let request = API2.sendRequest(bookId);

                    request
                        .buffer(true)
                        .end(function (err, res) {

                            if (err) {
                                failureList.push(bookId);
                                return console.error(err);
                            }

                            let data = {
                                body: res.body,
                                text: res.text
                            };

                            let data = data.text;

                            if (data == undebookIded || data == null) {
                                failureList.push(bookId);
                                return console.error("DATA NOT FOUND".red);
                            }

                            let privateKey = "./resource/priv_key.pem";

                            var jweParts = data.split(".");
                            security.decryptJWE(jweParts[0], jweParts[1], jweParts[2], jweParts[3], jweParts[4], privateKey)
                                .then(data => {
                                    if (data == undefined || data == null) {
                                        failureList.push(bookId);
                                        return console.error("INVALID DATA OR SIGNATURE FOR DATA".red);
                                    }

                                    let name = data.name.value;
                                    let desc = data.desc.value;
                                    let tag = data.tag.desc;
                                    let status = data.status.value;


                                    let updatedDate = converter.formatDate(new Date());
                                    let updatedBy = constant.DEFAULT__USERNAME;

                                    updateParam1.push(tag, updatedDate, updatedBy,
                                        bookId);

                                    updateParam2.push(tag, updatedDate, updatedBy,
                                        bookId);

                                    //Point A
                                    shelfDao.updateShelf(updateParam1, bookId, function (updateResult) {

                                        if (updateResult[1] === 1) {
                                            removalList.push(updateResult[0]);
                                        }
                                        else {
                                            failureList.push(updateResult[0]);
                                        }
                                    });

                                    //Point B
                                    libDao.updateLib(updateParam2, function (updateLibResult) {
                                        if (updateLibResult[1] === 1) {
                                            removalList.push(updateLibResult[0]);
                                        }
                                        else {
                                            failureList.push(updateLibResult[0]);
                                        }
                                    });

                                    //POINT C
                                    if (i === updateList.length) {

                                        //log number of success/fail/total.
                                        console.log(format(message.PROGRESS_MSG, removalList.length, failureList.length, updateList.length));
                                    }
                                })
                                .catch(error => {
                                    failureList.push(bookId);
                                    console.error("Error with decrypting JWE: %s".red, error);
                                })
                        });
                }
            });
        }
        else {
            return;
        }
    });
}

Образец класса DAO:

function updateShelf(params, bookId, callback) {
    pool.open(connString, function (err, conn) {

        conn.prepare(query.SQL_UPDATE_SHELF, function (error, stmt) {

            if (err) {
                console.error(err);
                return conn.closeSync();
            }

            stmt.executeNonQuery(params, function (err, result) {
                if( err ) {   
                    console.error(err);  
                }
                else {
                    console.debug("Affected rows = " + result);
                }

                //Close the connection
                conn.close();

                //return result as callback. 
                return callback([bookId, result]);
            });
        });
    });  
}

Класс безопасности:

security.decryptJWE = function decryptJWE(header, encryptedKey, iv, cipherText, tag, privateKey) {
  console.log("Decrypting JWE".green + " (Format: " + "header".red + "." + "encryptedKey".cyan + "." + "iv".green + "." + "cipherText".magenta + "." + "tag".yellow + ")");
  console.log(header.red + "." + encryptedKey.cyan + "." + iv.green + "." + cipherText.magenta + "." + tag.yellow);
  return new Promise((resolve, reject) => {

    var keystore = jose.JWK.createKeyStore();

    console.log((new Buffer(header, 'base64')).toString('ascii'));

    var data = {
      "type": "compact",
      "ciphertext": cipherText,
      "protected": header,
      "encrypted_key": encryptedKey,
      "tag": tag,
      "iv": iv,
      "header": JSON.parse(jose.util.base64url.decode(header).toString())
    };
    keystore.add(fs.readFileSync(privateKey, 'utf8'), "pem")
      .then(function (jweKey) {
        // {result} is a jose.JWK.Key
        jose.JWE.createDecrypt(jweKey)
          .decrypt(data)
          .then(function (result) {
            resolve(JSON.parse(result.payload.toString()));
          })
          .catch(function (error) {
            reject(error);
          });
      });

  })
    .catch(error => {
      console.error("Error with decrypting JWE: %s".red, error);
      throw "Error with decrypting JWE";
    })
}

API2:

'use strict';

const querystring = require('querystring');
const _ = require('lodash');
const restClient = require('superagent-bluebird-promise');

const security = require('./security.js');

const constant = require('../common/constant.js');

function sendRequest(bookId) {
    let url = "";

    url = ((secure) ? constant.HTTPS : constant.HTTP) + urlDomain + urlProp1 + "/" + bookId + "/";

    let method = "GET";
    let authType = "L2";

    let key1 = "./resource/1.pem";
    let key2 = "./resource/2.pem";

    let timestamp = (new Date).getTime();

    let extHeader = security.generateAuthorizationHeader(
        url
        , null
        , method
        , ""
        , authType
        , clientAppId1
        , key1
        , clientSecret
        , realm
        , "e"
        , timestamp
    );

    let intHeader = security.generateAuthorizationHeader(
        url
        , null
        , method
        , ""
        , authType
        , clientAppId2
        , key2
        , clientSecret
        , realm
        , "i"
        , timestamp
    );

    let cacheCtl = "no-cache";

    let strHeaders = "Cache-Control=" + cacheCtl;
    let headers = querystring.parse(strHeaders);

    let authHeaders = extHeader + ", " + intHeader;

    _.set(headers, "Authorization", authHeaders);

    let request = restClient.get(url);

    if (!_.isUndefined(headers) && !_.isEmpty(headers)) {
        request.set(headers);
    }

    return request;
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...