gpt4 book ai didi

javascript - ES6 - Promise.all 在 Promise.resolve 中

转载 作者:搜寻专家 更新时间:2023-10-31 23:53:18 25 4
gpt4 key购买 nike

我正在使用 ecmascript 6 并尝试在 Promise.resolve() 中一起执行 Promise.all()我的 API。

这是我的代码:

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. 更新位置
  2. unLinkUserToPosition
  3. linkUserToPosition
  4. getPositionAndCommittees - 此函数使用 getPositiongetCommittees 调用 Promise.all 并且应该在 getPosition() 和 getCommittees() 完成执行并返回格式化的 JSON 数据
  5. send.success - 这只是输出应该从 formatJSON 返回的 JSON

它现在执行的方式是从 linkUserToPosition 返回的数据作为 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 都将立即启动。发送功能也是如此,但由于它们返回一个稍后将执行的功能,所以没问题。这意味着函数立即执行,并将生成的 promise 分配给前一个函数的 .then() - 这没有意义,因为 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));

关于javascript - ES6 - Promise.all 在 Promise.resolve 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com