简体   繁体   中英

How to chain two promises in Node.js?

I am new to Node.js. I want to chain two promises. When the first promise fails, the second promise should not be executed. But my code below always executed the second promise when the first promise failed.

function genQueryPromise(query, parameters) {
  var deferred = Q.defer();
  dbClient.executeAsPrepared(query, parameters,
    function(err) {
      if (err) {
        console.log(
            'error in query: ' + query + ", parameters: " + parameters);
        deferred.reject(new Error(err));
      } else {
        console.log("Query succeeded: " + query);
        deferred.resolve();
      }
    }
  );
  return deferred.promise;
}

var timeUuid = cql.types.timeuuid();
genQueryPromise(
    'INSERT INTO points_statement ' +
      '(user_id, statement_id, points_change, time_updated, note) ' +
    'VALUES (?, ?, ?, dateof(now()), ?)',
    ["mytest8",
     timeUuid,
     220,//{value: pointsChange, hint: cql.types.dataTypes.bigint},
     "test"]
  )
  .then(genQueryPromise(
    'UPDATE user_points SET points = points + ? WHERE user_id = ?',
    [{value: 220, hint: cql.types.dataTypes.bigint}, "mytest8"]
  ))
  .fail(function (error) {
    console.log("db error " + error);
  });

The output is below:

error in query: INSERT INTO points_statement (user_id, statement_id, points_change, time_updated, note) VALUES (?, ?, ?, dateof(now()), ?), parameters: mytest8,b5835850-2266-11e4-a871-f1a82b5a7753,220,test
db error Error: ResponseError: Expected 8 or 0 byte long (4)
Query succeeded: UPDATE user_points SET points = points + ? WHERE user_id = ?

You can see that the second promise was execute even when the first promise failed. What did I do wrong? Thanks.

You are calling genQueryPromise while constructing the promise chain. Call from it within the chain:

genQueryPromise(
    'INSERT INTO points_statement ' +
      '(user_id, statement_id, points_change, time_updated, note) ' +
    'VALUES (?, ?, ?, dateof(now()), ?)',
    ["mytest8",
     timeUuid,
     220,//{value: pointsChange, hint: cql.types.dataTypes.bigint},
     "test"]
  )
  .then(function() {
    return genQueryPromise(
      'UPDATE user_points SET points = points + ? WHERE user_id = ?',
      [{value: 220, hint: cql.types.dataTypes.bigint}, "mytest8"]
    );
  })
  .fail(function (error) {
    console.log("db error " + error);
  });

Adding a function wrapper makes it so that the second call is executed after the first call is complete, instead of both at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM