ES6 - Promise.all 在 Promise.resolve 内

ES6 - Promise.all within a Promise.resolve

我正在使用 ecmascript 6 并试图在我的 API.

中一起执行 Promise.resolve() 中的 Promise.all()

这是我的代码:

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 进行数据库查询,这意味着当我 return Database.connection.query() 时,它实际上是 return 一个新的 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. 更新位置
  2. unLinkUserToPosition
  3. linkUserToPosition
  4. getPositionAndCommittees - 此函数使用 getPositiongetCommittees 调用 Promise.all 并且应该在 getPosition() 和 getCommittees() 完成执行后立即调用 formatJSON和 return 格式化的 JSON 数据
  5. send.success - 这只是输出 JSON 应该 return 从格式 JSON

它现在的执行方式是从 linkUserToPosition 编辑的数据 return 被 return 编辑为 send.success 函数中的数据,这意味着Promise.resolve 没有等待 getPositionAndCommittees 完成执行 Promise.all

输出结果如下:

{
  "fieldCount": 0,
  "affectedRows": 1,
  "insertId": 0,
  "serverStatus": 2,
  "warningCount": 0,
  "message": "(Rows matched: 1  Changed: 0  Warnings: 0",
  "protocol41": true,
  "changedRows": 0
}

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

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

假设这个调用链:

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

这意味着异步函数updatePositionunLinkUserToPositionlinkUserToPositiongetPositionAndCommittees都将立即启动。发送功能也是如此,但是由于这些 return 稍后将执行的功能,所以没问题。这意味着函数立即执行,并将生成的承诺分配给前一个函数的 .then() - 这没有意义,因为 then 接受一个函数(可能 return 一个承诺),而不是一个承诺。您需要的是:

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));