多重承诺 - 在哪里解决?

时间:2018-04-21 13:47:39

标签: javascript promise

我是新的承诺。

我正在使用nodejs promisify,所以我将以下声明声明为Redis的承诺

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

如果我将解决方案(消息)放在现在的位置,则上述承诺无法解决,并且“发送消息结果”根本不显示。

如果我将它放在链承诺之外,则var消息返回一个空对象{}

我的问题:我需要将解决方案放在需要多次承诺调用的此类函数中,因为我需要等待多次redis检查?

我有许多功能需要在我继续进行下一步操作之前进行所有redis调用。

1 个答案:

答案 0 :(得分:1)

我可能会考虑重构您的代码,如下所示。如果您需要在临时.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);
}