【问题标题】:Wait for query result of Bookshelf insert等待书架插入的查询结果
【发布时间】:2017-11-14 12:43:35
【问题描述】:

基本上我需要等待使用Bookshelf.js 进行的insert 查询的结果,因为我需要查询提供的id 在我的数据库中插入一行

我不了解 Node 及其组件的异步行为的某些方面

所以问题出在这部分代码上:

插入方法书架

var new_timer = new Timer({
                titolo: title,
                time: timerVal,
                created: creation,
                ended: ended,
                id_owner: owner
            });
new_timer.save(null, {method: "insert"}).then(function(model){
    if(!model)
        return res.send({status: 400, url: "/add"});
    associateTag(model.id_timer, tags);
    return res.send({status: 200, url: "/"});
});

使用的功能

var insertAssociation = function(timerID, tags) {
     return knex.table('timer_tag').insert({id_tmr: timerID, id_tg: tags.id_tag});
}

var associateTag = function(timerID, tags) {
    var id_tag;
    for(var i = 0; i < tags.length; i++){
        getTagByName(tags[i]).then(function(result) {
            console.log(result);
            insertAssociation(timerID, result[0]).then(function(k) {
                console.log(k);
            });
        });
    }
}

var getTagByName = function(name) {
    return knex.table('tags').select('id_tag').where('nome_tag', name);
}

【问题讨论】:

标签: javascript mysql node.js bookshelf.js


【解决方案1】:

替换

for(var i = 0; i < tags.length; i++){
        getTagByName(tags[i]).then(function(result) {
            console.log(result);
            insertAssociation(timerID, result[0]).then(function(k) {
                console.log(k);
            });
        });
    }

Promise.all(tags.map(x => getTagByName(x)
   .then((result) => insertAssociation(timerID, result[0]))))

您正在异步启动多个请求。我所做的是使用Promise.all 来等待所有这些请求完成。


编辑:完整示例

  new_timer.save(null, {
    method: 'insert',
  }).then((model) => {
    if (!model) {
      res.send({
         status: 400,
         url: '/add',
      });

      return;
    }

    associateTag(model.id_timer, tags)
      .then((allRets) => {
          console.log(allRets);

          res.send({
            status: 200,
            url: "/"
          });
      })
      .catch(e => {
        // error handling
      });
  })
  .catch(e => {
    // error handling
  });

  var associateTag = function (timerID, tags) {
    return Promise.all(tags.map(x => getTagByName(x)
      .then((result) => insertAssociation(timerID, result[0]))));
  }

【讨论】:

  • 我试图替换您提供的代码,但它不起作用...我试图记录timerID,但它返回undefined
  • 所以我设法解决了这个问题...我使用了错误的model 元素,我用model.attributes.id_timer 替换了model.id_timer,现在由于您的回答,我更好地理解了异步行为
猜你喜欢
  • 2017-10-30
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 2019-04-19
  • 2012-10-28
  • 2014-03-03
相关资源
最近更新 更多