Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
建立JavaScript承诺_Javascript_Node.js - Fatal编程技术网

建立JavaScript承诺

建立JavaScript承诺,javascript,node.js,Javascript,Node.js,我正试着用JavaScript来理解承诺。我觉得我知道什么是承诺。然而,我不知道如何使用它们。为了学习,我决定从Node.js查询数据库。在我的代码中,我有一个名为test.js的JavaScript文件。Test.js如下所示: Test.js 'use strict'; module.exports = function (app) { var customerService = require('customer.js')(app); var getCustomerTest =

我正试着用JavaScript来理解承诺。我觉得我知道什么是承诺。然而,我不知道如何使用它们。为了学习,我决定从Node.js查询数据库。在我的代码中,我有一个名为test.js的JavaScript文件。Test.js如下所示:

Test.js

'use strict';

module.exports = function (app) {
  var customerService = require('customer.js')(app);

  var getCustomerTest = function() {
    customerService.getCustomer(1).then(
      function (customer) { console.log(customer); },
      function (error) { console.log(error); }
    );
  };
};
'use strict';

module.exports = function(app) {
  var _ = require('lodash');
  var db = require('db');

  return {
    getCustomer: function(customerID) {
      try {
        console.log('querying the database...');
        var database = db.connect(CONNECTION_STRING);
        database.query('select * from customers where [ID]="' + customerID + '", function(error, result, response) {
          if (error) {
            // trigger promise error
          } else {
            // This throws an exception because displayMessage can't be found.
            this.displayMessage('Success');

            // trigger promise success
          }
        });
      } catch (ex) {
        // trigger promise error
      }
    },

    displayMessage: function(message) {
      console.log(new Date() + ' - ' + message);
    }
  };
};
Customer.js

'use strict';

module.exports = function (app) {
  var customerService = require('customer.js')(app);

  var getCustomerTest = function() {
    customerService.getCustomer(1).then(
      function (customer) { console.log(customer); },
      function (error) { console.log(error); }
    );
  };
};
'use strict';

module.exports = function(app) {
  var _ = require('lodash');
  var db = require('db');

  return {
    getCustomer: function(customerID) {
      try {
        console.log('querying the database...');
        var database = db.connect(CONNECTION_STRING);
        database.query('select * from customers where [ID]="' + customerID + '", function(error, result, response) {
          if (error) {
            // trigger promise error
          } else {
            // This throws an exception because displayMessage can't be found.
            this.displayMessage('Success');

            // trigger promise success
          }
        });
      } catch (ex) {
        // trigger promise error
      }
    },

    displayMessage: function(message) {
      console.log(new Date() + ' - ' + message);
    }
  };
};
我正在努力在getCustomer中设置承诺。尤其是因为对数据库调用的调用是异步进行的。我觉得打电话给customerService.getCustomer是正确的方法。但是,一旦进入getCustomer,我就有两个问题:

  • 我如何设定/回报我的承诺
  • 为什么我不能在数据库查询完成后调用displayMessage?我该怎么做
  • 谢谢你

    “为什么我不能在数据库查询完成后调用displayMessage”

    出现错误是因为
    未引用包含
    getCustomer
    displayMessage
    的对象。这是因为您处于回调函数中,并且上下文已更改

    您需要保存对正确上下文的引用,并使用该引用访问
    displayMessage

    getCustomer: function(customerID) {
      //saving the context
      var that = this;
      try {
        ...
        database.query('select * from customers where [ID]="' + customerID + '", function(error, result, response) {
            ...
            // Now use it here to call displayMessage
            that.displayMessage('Success');
            ...
          }
        });
      } catch (ex) {
        ...
      }
    },
    
    “我如何设定/回报我的承诺?”

    您将需要一个promise库(除非您计划创建自己的库)。为此,我将展示

    有几种方法可以做到这一点,但我将展示延迟的用法

    基本过程是:

  • 在将调用异步函数/方法的函数中创建延迟对象
  • 返回承诺对象
  • 为promise对象上的then/fail/fin等设置适当的回调
  • 在异步函数的回调中,解析或拒绝延迟,传递回调中需要的任何参数
  • 然后将按顺序调用在步骤2中设置的相应回调 代码

    q库有很多有用的api函数。有些帮助可以获得节点异步函数的承诺。阅读自述文件的一节,了解它是如何完成的

    演示在浏览器中使用q

    查看两个模块“q”-并且,不是为了承诺,而是为了异步回调,还有“async”-。它们都有很好的文档,是您解决此问题所需的。