javascript - 回调已经被调用!在环回中,在 updateAll 函数中

标签 javascript node.js loopbackjs strongloop loopback

我在这里使用环回,同时使用数组中的对象列表进行更新调用。

我发现回调已经被调用了!

场景是,我在循环内部定义了回调,并且在第一个循环中,实际调用了它。

我正在寻找那条路

我应该更新查询 MySQL 计划调用中的所有对象列表。

    Inward.updateIsActiveDetails = function(data, callback) {
        var id = _.map(data, 'id');
        if (id.length > 0) {
          _.forEach(id, id => {
            console.log('id....:', id)
            Inward.updateAll({id}, {
              isActive: 0,
            }).then(updateresult => {
              console.log(updateresult);
   // callback(error); showing err with it... (callback already called)
            }).catch(function(error) {
              callback(error);
            });
          });
        } else {
          callback(null, {
            success: true,
            msg: 'No records to update',
          });
        }
      };

输出:

id....: 3
id....: 4
{ count: 1 }
{ count: 1 }

感谢正确的解决方案

最佳答案

回调应该被调用一次,您在循环中调用它,因此循环的每次迭代都会调用它。不止一次。如果出于某种原因您无法使用 async/await,则以下内容是正确的。

Inward.updateIsActiveDetails = function(data, callback) {
    var id = _.map(data, 'id');
    var len = id.length;
    var resultList = [];

    // When you call this function we add the results to our list
    // If the list of updates is equal to the number of updates we had to perform, call the callback.
    function updateResultList(updateResult) {
      resultList.push(updateResult);
      if (resultList.length === len) callback(resultList);
    }
    if (len > 0) {
      _.forEach(id, id => {
        Inward.updateAll({id}, {
          isActive: 0,
        })
        .then(updateResult);
      });
    } else {
      callback(null, {
        success: true,
        msg: 'No records to update',
      });
    }
  };

使用 async/await 会短得多。

Inward.updateIsActiveDetails = async function(data) {
  const results = [];
  for(let i = 0; i < data.length; i++) {
    results.push(await Inward.updateById(data[i].id));
  }
  return results;
}

关于javascript - 回调已经被调用!在环回中,在 updateAll 函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55890879/

相关文章:

javascript - 使用 swiper.js 库使用react的 CSS 冲突

node.js 和 expressjs 渲染带有 URL 参数的模板

javascript - 在 NodeJS 中创建 HTTPS 客户端

javascript - 如何使用 sequelize 在 where 子句中添加 "or"语句

mysql - 环回: saving model relations to database

node.js - 如何在环回中更新多个对象?

javascript - 函数定义在一行

php - Jquery Slider 有时会出现在奇怪的位置

javascript - WinJS自定义控件: winControl undefined

node.js - Node 环回+API响应返回二进制数据