0

I have the following codes: First, it sends a package to the back-end using socket.emit, once it is done, initialize the chat

var socket = io();

send_package(socket, user_uid, match_uid, room_id, user_data).then(() => {
  initializeChat(socket, user_uid, match_uid, room_id, user_data, 
  displayed_name, ll_location, ll_language, ll_level, ll_interests);
})


function send_package(socket, user_uid, match_uid, room_id, user_data) {

  socket.on("connect", () => {
    console.log("1");
    socket.emit("match_package", {user_uid, match_uid, room_id, user_data});
  })
  return new Promise((resolve, reject) => {
    if (true) {
      resolve();
    } else {
      reject();
    }
  })
}

I feel that I did not use the promise correctly, because the initalizeChat function gets executed before send_package.

Your help and time is very appreciated.

Sincerely

Chen
  • 860
  • 10
  • 32
  • `if (true) { ... } else { ... }`? Under what circumstances will the else get called? In any case, `on` is asynchronous; resolve or reject the promise within its callback. – Heretic Monkey Apr 25 '19 at 18:56
  • Your intuition is right :] I've found a duplicate and closed it as such. Happy coding! – Benjamin Gruenbaum Apr 25 '19 at 18:56
  • Also see https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises – Benjamin Gruenbaum Apr 25 '19 at 18:57
  • Your nearly there, make the whole function the Promise,.. then use the the emit callback ack to resolve with.. `return new Promise(resolve => socket.emit("match_package", {user_uid, match_uid, room_id, user_data}, resolve);` – Keith Apr 25 '19 at 19:16

0 Answers0