0

Environment

Jquery2.0.3

What I want to do

(like chatapp messanger)

select image file and display as preview

submit

delete preview place

Code

async function send() {
    sendMessage(); // send text(omit detail)
    await sendImage(); // send image
    resetAfterSending(); // delete preview display
}

function sendImage() {
    return new Promise(res => {
        messages.append(`
            <div class=".preview-img">
                <img src="${$('.hoge2').find('img').attr('src')}">
            </div>
        `);

        return messages.ready(() => {
            return res();
        });
    });
}

function resetAfterSending() {
    /**
     * if I use hide() instead of remove(), element remains in DOM element(you can see in chrome elements panel)
     * But in this time, I need to delete in DOM element as well
     */
    $('.preview-img').remove();
}

trouble

When I didn't use async/await, resetAfterSendingMessage() was executed and there was no .preview-img element in DOM, so I coudn't even send image data. That's why I tried to use async/await like code at the top.

But when I tried to change like that ↓ ,image could be sent.

function send() {
    sendMessage();
    sendImage(); 
    //**use setTimeout()  !!
    setTimeout(() => {
        resetAfterSending();
    },0);
}

I think async/await executes function, but not finish rendering. This causes problem. (I even don't know it's true or not)

If I need to execute function after rendering, I need to use setTimeout() as THIS LINK says?

If somebody knows the way instead of setTimeout(), plz comment it out here.You know setTimeout() is not kinda cool, hope you get what I mean.

kazon
  • 344
  • 1
  • 4
  • 15

1 Answers1

0

Since sendImage() returns a Promise, you could use .then()

sendImage().then(() => resetAfterSending());
Balastrong
  • 4,336
  • 2
  • 12
  • 31
  • "then" executes after finishing function, but not after finishing render right? I just think so, and unfortunately i didnt find article about that. – kazon Jun 14 '20 at 10:24