简体   繁体   English

将 javascript 函数与 promise 同步,socket.io 发出

[英]Synchronizing javascript functions with promises, socket.io emit

I'm building a web app and am trying to emit data to a server in a particular order, using socket.io's emit().我正在构建一个 web 应用程序,并尝试使用 socket.io 的 emit() 以特定顺序将数据发送到服务器。 Basically, I'm trying to send two sets of data synchronously and then a "submit" message after both previous sets of data ( steps and files ) are completely sent.基本上,我试图同步发送两组数据,然后在完全发送之前的两组数据( stepsfiles )之后发送“提交”消息。 My problem is that the "submit" message is sent before the files has finished being sent.我的问题是“提交”消息是在文件发送完成之前发送的。 I'm trying to use Promises but it's not working, and I'm guessing there's a mistake with the usage.我正在尝试使用Promises ,但它不起作用,而且我猜测用法有误。

sendToServer() {
    Promise.all([
        new Promise((res) => res(this.sendSteps())),
        new Promise((res) => res(this.sendFiles()))
    ]).then(this.sendSubmit());
}

Update:更新:

I also tried this but it doesn't solve the problem.我也试过这个,但它并没有解决问题。 sendSubmit() still starts before sendFiles() is done. sendSubmit() 仍然在 sendFiles() 完成之前启动。

async sendToServer() {
    return new Promise((res, rej) => res(this.sendSteps()))
        .then(() => {
            return new Promise((res, rej) => res(this.sendFiles()));
        })
        .then(() => {
            return new Promise((res, rej) => res(this.sendSubmit()));
        });
}

Please rewrite the code like this and let me know.请像这样重写代码并告诉我。

sendToServer() {
    Promise.all([
        new Promise((resolve, reject) => resolve(this.sendSteps())),
        new Promise((resolve, reject) => resolve(this.sendFiles()))
    ]).then(()=>{
        this.sendSubmit();
 });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM