2

我有一个函数可以做两件事需要 I/O 时间,我想第二次返回它,但我希望在这段时间内处理另一件事并快速发送,即使第一件事还没有完成

getuser(x){
    let username = getUsernameDB(x.id);//takes time to get data it is an async function

    sendMessage(x.id,() => {//send message with callback function when it is recived
       sendMessage(username);//must wait for getUsernameFromDatabase
    });

}

async getUsernameDB(id){
return await this.dataaccess.getUsernameByUserId(id);//this returns new Promise
}

所以我主要想做出一个承诺,执行其他代码然后在这里等待这个承诺解决然后继续。

4

1 回答 1

-1

.then 应该放在第一个 sendmessage 调用之后。这将使 promise 函数与 sendmessage 并行运行,然后在发送第二条消息之前等待解决

getuser(x){
    let username = getUsernameDB(x.id);//takes time to get data it is an async function

    sendMessage(x.id,() => {//send message with callback function when it is recived
        username.then((usernameVar) => {
            sendMessage(usernameVar);//usernameVar is carring the value now
    })

    });

}

async getUsernameDB(id){
return await this.dataaccess.getUsernameByUserId(id);//this returns new Promise
}
于 2018-06-09T04:07:21.337 回答