我有一个函数做两件事,某件事需要 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
}
所以我主要想做一个 promise ,执行其他代码然后在这里等待这个 promise 解决然后继续。
最佳答案
.then 应该放在第一个 sendmessage 调用之后。这将使 promise 函数与 sendmessage 并行运行,然后在发送第二条消息之前等待 resolve
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
}
关于javascript - 等待 promise 解决并在它解决时做其他事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50770639/