gpt4 book ai didi

javascript - 多重 promise - 在哪里解决?

转载 作者:行者123 更新时间:2023-12-03 02:02:14 28 4
gpt4 key购买 nike

我刚开始 promise 。

我正在使用nodejs promisify,因此我将以下内容声明为Redis的 promise

const { promisify } = require('util');
const getAsync = promisify(client.get).bind(client);
const hmsetAsync = promisify(client.hmset).bind(client);
const hsetAsync = promisify(client.hset).bind(client);
const incrAsync = promisify(client.incr).bind(client);
const smembersAsync = promisify(client.smembers).bind(client);
const keysAsync = promisify(client.keys).bind(client);
const sismemberAsync = promisify(client.sismember).bind(client);

我有以下函数,但我不知道放置解析(消息)的正确位置

function sendMessage(senderId = '', roomId = '', text = '', type='text') {

var message = {}
return new Promise( function (resolve, reject) {

if (senderId == '') {
reject('Invalid Characters in Sender Id or Sender Id is empty.');
}


if (roomId == '') {
reject('Invalid Characters in Room Id or Room Id is empty.');
}

if (text == '') {
console.log('Text:' ,text);
reject('Invalid Characters in Text or Text is empty.');
}
//Check if Room Exist

keysAsync('room-'+roomId).then((value) => {

value == '' && reject('Room '+roomId+ ' does not exist.');
sismemberAsync('roomuser-'+roomId, senderId).then((ismember)=> {
ismember == 0 && reject('User ' + senderId + ' is not a member of room ' + roomId);

const datetime = new Date();
incrAsync('messageId')
.then((id) => {
//Create the message Hash
hmsetAsync('messsage:'+id, 'id', id, 'roomId', roomId, 'senderId', senderId, "created", datetime, "text", text);
//add message to Set
saddAsync('roommessages-'+roomId, id);

message = { id: id, roomId: roomId, senderId: senderId, created: datetime, text: text }
resolve(message) //If i place here i don't get the resolve.

}).catch(err => reject(err))

}).catch(err => reject(err))

}).catch(err => reject(err))
})
}

然后我尝试像这样调用该函数

tools.sendMessage(3, 4, 'Does this work?','text').then((result)=> {
console.log('Send Message Result => ',result);
}).catch(err => {
console.log(err)
});

如果我将解析(消息)放在现在的位置,则上述 promise 不会解析,并且“发送消息结果”根本不会显示。

如果我将其放置在链 promise 之外,则 var 消息将返回一个空对象{}

我的问题:在这种需要多次 Promise 调用的函数中,我应该将解析放在哪里,因为我需要等待多次 Redis 检查?

我有许多函数,需要先执行所有 redis 调用,然后才能继续执行下一步操作。

最佳答案

我可能会考虑按如下方式重构您的代码。如果您需要临时捕获错误 .then()然后阶段使用 onrejected 回调。

function sendMessage(senderId = '', roomId = '', text = '', type='text') {
return keysAsync('room-'+roomId)
.then(value => value === '' ? Promise.reject('Room '+roomId+ ' does not exist.')
: sismemberAsync('roomuser-'+roomId, senderId))
.then(ismember => ismember === 0 ? Promise.reject('User ' + senderId + ' is not a member of room ' + roomId)
: incrAsync('messageId'))
.then(id => { var datetime =new Date();
hmsetAsync('messsage:'+id, 'id', id, 'roomId', roomId, 'senderId', senderId, "created", datetime, "text", text);
saddAsync('roommessages-'+roomId, id);
return { id: id, roomId: roomId, senderId: senderId, created: datetime, text: text };
})
.then(message => doSomethingWith(message))
.catch(errorHandler);
}

在上面的代码中我移动了new Date()到实际使用的下一级,但是如果由于某种原因您需要 datetime原文.then()如您问题中所示的阶段,那么您不妨执行以下操作;

function sendMessage(senderId = '', roomId = '', text = '', type='text') {
return keysAsync('room-'+roomId)
.then(value => value === '' ? Promise.reject('Room '+roomId+ ' does not exist.')
: sismemberAsync('roomuser-'+roomId, senderId))
.then(ismember => ismember === 0 ? Promise.reject('User ' + senderId + ' is not a member of room ' + roomId)
: Promise.all([incrAsync('messageId'), new Date()]))
.then(([id, datetime]) => { hmsetAsync('messsage:'+id, 'id', id, 'roomId', roomId, 'senderId', senderId, "created", datetime, "text", text);
saddAsync('roommessages-'+roomId, id);
return { id: id, roomId: roomId, senderId: senderId, created: datetime, text: text };
})
.then(message => doSomethingWith(message))
.catch(errorHandler);
}

关于javascript - 多重 promise - 在哪里解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49956438/

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