2016-03-20 10 views
1

私はエクスプレスアプリケーションでsqlite3を使用しようとしています。 基本的には、残りのリクエストに基づいて外部RESTリクエストにクエリを実行して、残りのリクエストを取得します。外部リクエスト&からの応答と元のRESTリクエストから渡されたデータとの間に、私はsqlite3テーブルの1つに更新または挿入を行います。nodejs sqlite3 db.runをブルーバードの約束として

私が遭遇している問題は、db.run(sqlStatement, paramArray, function(err))では、関数(err)がコールバックで、errがエラーまたはnilのいずれかであることです。それに加えて、errのパラメータがnullの場合、thisの参照には2つのプロパティがあり、そのうちの1つはステートメントによって変更された行の数を示します。 (参照用https://github.com/mapbox/node-sqlite3/wiki/API#databaserunsql-param--callback

事は、私は青い鳥のpromisifyAll sqlite3のモジュール上を実行し、だから私は実際には何が更新されたかどうかを把握することができませんでしだ結果

db.runAsync(sqlStatement, paramArray).then(err) { 
    console.log(this) //results in a null 
} 

を使用し、です。コードの

私のセクション全体が少し次のようになります。

function handleRequest(req, res) { 

    //this returns the response as the first object 
    request.getAsync('http://www.example.com', reqObj)   
     .then(prepareDbObjects) //prepares an array of objects to update the DB with 
     .then(attemptUpdate) 
     .then(function(rowsUpdated) { 
      res.json(rowsUpdated) 
     } 
} 

function attemptUpdate(updateObjs) { 
    var promiseMap = Promise.map(updateObjs, function(singleObj) { 
     return updateOrInsertObj(singleObj) 
    } 
    return promiseMap 
} 


function updateOrInsertObj(singleObj) { 
    return db.runAsync(sqlStatement, singleObj) 
     .then(function(err) { 
      if(err) { 
       //handle error 
      } else { 
       console.log("this should be an object with 2 properties", this) 
       //but instead it is null 
      } 
     } 
} 

答えて

3

それはむしろとしてよりも、成功したコールバック関数にthisを返す方法を私はnode-sqlite3コードで見て行き、私はかなり確信しています実際のパラメータですが、問題です。つまり、適切な戻り値がないため、bluebirdのmultiArgs=trueパラメータを使用しようとしても機能しませんでした。

私は自分のカスタムプロミスメソッドでdb.run関数をラップしようとしましたが、そのトリックを行うように見えました。

具体的には、私がやった:

function runCustomAsync(sql, params) { 
    return new Promise(function(resolve, reject) { 
     db.run(sql, params, function cb(err) { 
      if(err) { 
       var responseObj = { 
        'error': err 
       } 
       reject(responseObj); 
      } else { 
       var responseObj = { 
        'statement': this 
       } 
       resolve(responseObj); 
      } 
     }); 
    }); 
} 

db.runCustomAsync = runCustomAsync; 
module.exports = db; 

それは、それが正常に処理されますかとは少し異なっています。現在、thisオブジェクトを含むオブジェクトを返すか、errオブジェクトを含む可能性があります。私の元の要求で

は、あなたが拒否 `呼び出している場合、私は今

db.runCustomAsync(sqlStatement, params) 
    .then(function(dbResponseObj) { 
     if(dbResponseObj.error) { 
      //handle error 
     } else { 
      //do stuff with dbResponseObj.statement 
     } 
    }) 
+2

を行う()'、なぜそれが ')(' .thenを打つでしょうか? – Danosaure