avatar
Promise and async/await Javascript

• First and foremost, Promise or Async/Await aims at resolving asynchronous threads while executing Rest APIs, background service to synchronize up with main User Interface or thread.

let p = new Promise(resolve => {
  ""(); 
  resolve();
});

(async () => {
  await p;
})().catch(e => console.log("Caught: " + e));

• From the above script, you are able to have several way of incorporations as below: 

async -> await
async -> new Promise((resolve) => {...})
async -> await new Promise((resolve) => {...})

• In case async » await new Promise({resolve} => {...}) or async » new Promise({resolve} => {...})

async function getTopic(topicID) {
    return await new Promise((resolve) => {
        Todo.findOne({topic_id: topicID}, function (err, data) {
            if (err !== null) {
                resolve(err);
            } else {
                resolve(data);
            }
        });
    });
}
or
async function getTopic(topicID) {
    return await Todo.findOne({topic_id: topicID});
}

let topicPromise = getTopic(topicID);
if (topicPromise == null) {
	// TODO
}

Note: How to access the value of a Promise? Let be attention on new Promise() or await upon successfully implement logic. It will return [object Promise].

• With [object Promise] is returned, we have some ways to access value. To be simple, we will separate into different of approaches.

» Only Promise

topicPromise.then(function(result) {
    // here you can use the result of promiseB
});

» Multiple Promise

const promis = this.getData(firstData);
const promis2 = this.getData(secondData);

Promise.all([promis, promis2])
  .then((results) => {
  // TODO
});

Note: In Multiple Promises, the response from promise and promise2 should be consistent with type of data.

• How can we apply for the real project? Here is an example to use Promise and Async/Await.

const Conversation = require('../models/Conversation');
const mongoose = require('../config/mongoose');
const Logger = require("../utils/logger");
const Topic = require('../models/Topic');

async function getConversationPromise(UUID) {
    return await new Promise((resolve) => {
        Conversation.findOne({conversation_id: UUID}, function (err, conversation) {
            if (err !== null) {
                resolve(err);
            } else {
                resolve(conversation);
            }
        });
    });
}

const convertDateToTimestamp = (date) => {
    return new Date(date).getTime();
}

const getTopicById = async (topicId) => {
    return await new Promise((resolve) => {
        Conversation.find({topic_id: topicId}, function(err, data) { 
            if (err !== null) {
                resolve(err);
            } else {
                resolve(data);
            }
        });   
    });
}

const addConversation = async(req, res) => {
    const UUID = 'UUID' + req.body.topic_id + req.body.user_id + convertDateToTimestamp(req.body.date_created);
    const promise = await getTopicById(req.body.topic_id);
    Promise.all([promise]).then(results => {
        Logger.info(results);
    });
    try {
        let promiseConn = await getConversationPromise(UUID);
        if (promiseConn == null) {
            const conversation = await Conversation.create({
                conversation_id: UUID,
                topic_id: req.body.topic_id,
                topic_name: req.body.topic_name,
                user_id: req.body.user_id,
                staff_id: null,
                date_modified: req.body.date_modified,
                date_created: req.body.date_created,
                messages: req.body.messages,
            });
            return res.json({
                success: true,
                message: "Conversation added successfully!",
            });
        }
    } catch (err) {
        return res.json({
            success: false,
            message: "Error with adding conversation. See server console for more info.",
        });
    }    
}

const getConversations = async (req, res) => {
    try {
        const conversation = await new Promise((resolve) => { 
            Conversation.find({}, function(err, data) { 
                if (err !== null) {
                    resolve(err);
                } else {
                    resolve(data);
                }
            }).sort({'date_modified': -1});
        }); 
        return res.json({
            success: true,
            conversation: conversation
        });
    } catch (error) {
        return res.json({
            success: false,
            conversation: error
        });
    }
};

const updateDateModifiedConversation = async (req, res) => {
    try {
        const conversation = await new Promise((resolve) => { 
            Conversation.findOneAndUpdate({conversation_id: req.body.conversationId}, { date_modified: req.body.dateModified }, { new: true }, function(err, data) { 
                if (err !== null) {
                    resolve(err);
                } else {
                    resolve(data);
                }
            });
        }); 
        return res.json({
            success: true,
            conversation: conversation
        });
    } catch (error) {
        return res.json({
            success: false,
            conversation: error
        });
    }
};

const getConversationByConversationId = async (req, res) => {
    try {
        const conversation = await new Promise((resolve) => { 
            Conversation.find({conversation_id: req.body.conversationId}, function(err, data) { 
                if (err !== null) {
                    resolve(err);
                } else {
                    resolve(data);
                }
            });
        }); 
        return res.json({
            success: true,
            conversation: conversation,
        });
    } catch (error) {
        return res.json({
            success: false,
            conversation: error
        });
    }
};

const addMessage = async (req, res) => {
    const MGSID = 'MGSID' + req.body.topicId + req.body.ownerMessageId + req.body.dateCreated;
    try {
        const conversation = await new Promise((resolve) => { 
            Conversation.updateOne({conversation_id: req.body.conversationId}, { $push: { messages: {
                message_id: MGSID,
                owner_message_id: req.body.ownerMessageId,
                message: req.body.message,
                date_created: req.body.dateCreated,
            } } }, function(err, data) { 
                if (err !== null) {
                    resolve(err);
                } else {
                    resolve(data);
                }
            });
        }); 
        return res.json({
            success: true,
            conversation: conversation,
        });
    } catch (error) {
        return res.json({
            success: false,
            conversation: error
        });
    }
};

module.exports = {
    addConversation,
    getConversations,
    getConversationByConversationId,
    addMessage,
    updateDateModifiedConversation,
};
24
You need to login to do this manipulation!