简体   繁体   English

如何在Node.js中链接两个诺言?

[英]How to chain two promises in Node.js?

I am new to Node.js. 我是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. 您在构造承诺链时正在调用genQueryPromise 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. 添加函数包装器可以使第二个调用在第一个调用完成后执行,而不是同时执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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