ES6 - Promise.all在Promise.resolve中

时间:2015-12-12 22:49:49

标签: javascript node.js promise ecmascript-6 es6-promise

我正在使用ecmascript 6并尝试在我的API中同时在Promise.all()内执行Promise.resolve()

这是我的代码:

import jwt from "jsonwebtoken";
import Database from "../../../util/Database";
import send from "../../../util/send";

var updatePosition = function(organizationId, positionId, positionTitle) {
  let updatedPosition = {
    organization_id: organizationId,
    title: positionTitle
  };
  return Database.connection.query('UPDATE positions SET ? WHERE id=?', [updatedPosition, positionId]);
}

var unLinkUserToPosition = function(positionId) {
  return Database.connection.query('UPDATE users SET position_id=NULL WHERE position_id=?', positionId);
}

var linkUserToPosition = function(positionId, userId) {
  return Database.connection.query('UPDATE users SET position_id=? WHERE id=?', [positionId, userId]);
}

var getPositionAndCommittees = function(positionId) {
  return Promise.all([getPosition(positionId), getCommittees(positionId)]).then(formatJSON);
}

var getPosition = function(positionId) {
  return Database.connection.query('SELECT \
    p.id as position_id, \
    p.title as position_title, \
    u.id as user_id, \
    u.facebook_UID, \
    u.email, \
    u.first_name, \
    u.last_name, \
    u.phone, \
    u.semester_joined, \
    u.year_joined, \
    u.thumbnail_photo_URL, \
    u.cover_photo_URL \
    FROM positions p \
    LEFT JOIN users u ON p.id=u.position_id \
    WHERE p.id=? \
    ORDER BY p.id ASC', positionId);
}

var getCommittees = function(positionId) {
  return Database.connection.query('SELECT \
    c.id as committee_id, \
    c.title as committee_title, \
    u.id as chairmen_user_id, \
    u.thumbnail_photo_URL as chairmen_thumbnail_photo_URL, \
    u.first_name as chairmen_user_first_name, \
    u.last_name as chairmen_user_last_name \
    FROM committees c \
    LEFT JOIN users u ON c.chairmen_id=u.id \
    WHERE c.position_id=? ORDER BY c.title ASC', positionId);
}

var formatJSON = function(results) {
  let positionResult = results[0][0];
  let committeesResult = results[1];
  let position = {
    id: positionResult.position_id,
    title: positionResult.position_title,
    user: {
      id: positionResult.user_id,
      facebookUID: positionResult.facebook_UID,
      email: positionResult.email,
      firstName: positionResult.first_name,
      lastName: positionResult.last_name,
      phone: positionResult.phone,
      semesterJoined: positionResult.semester_joined,
      yearJoined: positionResult.year_joined,
      thumbnailPhotoURL: positionResult.thumbnail_photo_URL,
      coverphotoURL: positionResult.cover_photo_URL
    },
    committees: committeesResult
  };

  return position;
}

module.exports = function(req, res) {
  let token = req.headers['bearer-authorization'];
  let tokenSecret = ENV.API_SECRET
  let decodedToken = jwt.verify(token, tokenSecret);

  let organizationId = 1
  let positionId = req.params.positionId;
  let positionTitle = req.body.title;
  let positionUserId = req.body.userId;

  Promise.resolve(updatePosition(organizationId, positionId, positionTitle))
    .then(unLinkUserToPosition(positionId))
    .then(linkUserToPosition(positionId, positionUserId))
    .then(getPositionAndCommittees(positionId))
    .then(send.success(res))
    .catch(send.failure(res));
};

旁注:我正在使用promise-mysql进行数据库查询,这意味着当我返回Database.connection.query()时,它实际上正在返回一个新的Promise

以下是send.successsend.failure函数的外观:

var send = {
  success: function(response) {
    return function(data) {
      response.status(200).json(data);
    };
  },
  failure: function(response) {
    return function(error) {
      var statusCode = error.statusCode || 500;

      if (statusCode === TEMPORARY_REDIRECT && error.body && error.body.value) {
          response.status(200).json(error.body.value);
          return;
      }

      console.error(error.stack);

      response.status(statusCode).json({
        message: error.message
      });
    };
  }
}

下面是我试图让我的函数执行的命令:

  1. updatePosition
  2. unLinkUserToPosition
  3. linkUserToPosition
  4. getPositionAndCommittees - 此函数使用getPositiongetCommittees调用Promise.all,并且一旦getPosition()和getCommittees()完成执行并返回格式化的JSON数据,就应该调用formatJSON
  5. send.success - 这只输出应该从formatJSON
  6. 返回的JSON

    现在正在执行的方式是从linkUserToPosition返回的数据作为send.success函数中的数据返回,这意味着Promise.resolve不等待{{ 1}}完成执行getPositionAndCommittees

    这是输出的样子:

    Promise.all

    关于如何完成我想要做的事情的任何建议都将不胜感激!

1 个答案:

答案 0 :(得分:2)

我认为问题是几个功能立即启动,而不仅仅是在前面的步骤完成之后。

假设这个调用链:

updatePosition(organizationId, positionId, positionTitle)
.then(unLinkUserToPosition(positionId))
.then(linkUserToPosition(positionId, positionUserId))
.then(getPositionAndCommittees(positionId))
.then(send.success(res))
.catch(send.failure(res));

这意味着异步函数updatePositionunLinkUserToPositionlinkUserToPositiongetPositionAndCommittees都将立即启动。发送功能也是如此,但是当它们返回将在稍后执行的功能时,它没有问题。这意味着函数执行immediatley,并将结果的promise分配给前一个函数的.then() - 这没有任何意义,因为它接受一个函数(可能返回一个promise),而不是一个promise。你需要的是:

updatePosition(organizationId, positionId, positionTitle)
.then(updatePositionResult => unLinkUserToPosition(positionId))
.then(unLinkUserToPositionResult => linkUserToPosition(positionId, positionUserId))
.then(linkUserToPositionResult => getPositionAndCommittees(positionId))
.then(send.success(res))
.catch(send.failure(res));