node.js - Promisfy 环回模型

标签 node.js loopbackjs strongloop

在单元测试 Loopback 中,有必要将回调与 upsert 方法结合使用。例如......而不是按照这样的方式写一些东西:

before(function () {

    Student = server.models.Student
    Course = server.models.Course


    Course.upsert({id: 1, key: 'A', department: 'Original department'})
    Student.upsert({id: 1, points: 5000})


})

有必要确保回调与更新插入一起使用。由于我有很多模型,所以我在下面初始化我使用异步:

before(function (done) {

    Student = server.models.Student
    Course = server.models.Course


    async.waterfall([
            function (callback) {
                Course.upsert({id: 1, key: 'A', department: 'Original department'}, callback)
            },
            function (f, callback) {
                Student.upsert({id: 1, points: 5000}, callback)
            },

        ],
        function (err, results) {
            done(err)
        })

})

如何将上面的代码更改为使用 Promises,而不是异步?

我的想法是,有了 Promise,我就能够编写一些如下所示的代码:

before(function (done) {

    Student = server.models.Student
    Course = server.models.Course


    Course.upsert({id: 1, key: 'A', department: 'Original department'})
      .then(Student.upsert({id: 1, points: 5000})
      .then(function(err) { done(err) } 


})

但我一直未能成功兑现 promise 。

编辑以下答案...

 before(function (done) {


    Course = server.models.Course

    Course.upsertWithPromise = Promise.promisify(Course.upsert)

    Course.upsertWithPromise({id: 1, key: 'A', department: 'Original department'})
        .then(done)

  } 




it.only('Course upsert', function (done) {

    Course.findById(1, function (err, course) {

        expect(course.id).to.equal(1)
        expect(course.department).to.equal('Original department')

        done()


    })
})

最佳答案

有两种可能的解决方案。首先是手动 promise 。 您的函数将如下所示:

server.models.Student.upsert = function(data) {  // Note NO CALLBACK
  return new Promise(function(resolve, reject) {
    // Here can do all async staff and when done sucessfully call:
    resolve(result);
    // OR on error call:
    reject(err);
  });
}

第二个解决方案将使用库来达到相同的目的。

  1. var q = require('q');//使用 q 库
  2. 请勿修改您的模型。他们必须将回调作为最后一个参数(遵循 Node 约定)
  3. var server.models.Student.upsertWithPromice = q.denodeify(server.models.Student.upsert);
  4. 利润。

那么您的示例中的代码应该可以正常工作。

关于node.js - Promisfy 环回模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930540/

相关文章:

javascript - Graphql:必须提供查询字符串

node.js - Strongloop环回中的hasMany和referencesMany有什么区别

node.js - Loopback - 模型 ACL 列表在数据库中查找,而不是在其 json 文件中查找

javascript - Strongloop - 使用 model.js 执行 PHP

javascript - Strongloop:隐藏 PersistedModel 上的默认方法

javascript - Chrome 检查器控制台不适用于版本 54.0.2840.99

javascript - 'Async Juggling' - 它真正要求我做什么?

javascript - 对于非实时网站/应用程序,node.js 是否过多?

access-token - 允许环回应用程序使用以前的访问 token

node.js - 如何为带有参数和关系的方法编写远程钩子(Hook)