在生锈中有相对新的特征,
async
和
await
.
一个这样的用法示例是,有websockets,您发送一条消息并等待特定消息返回,但只有一个
onMessage
还有一个
sendMessage
整个应用程序。
因此,我尝试在Javascript中使用
setInterval
运行时钟(模拟多个
websockets的事件。
如何用Rust/或Tokio编写这个Javascript呢?。再一次,我并不是为了这个代码,而是为了概念性的
使方法调用等待相应的响应。
let setAlarm = (seconds) => {
return new Promise((resolve, reject) {
if(seconds > 60 || seconds < 0) {
return reject(new Error("Invalid seconds"));
}
//Represents going through many messages
//waiting for the matching id indicating
//its a reply to my original message
let handle = setInterval(function() {
let date = new Date();
if(date.getSeconds() == seconds) {
clearInterval(handle);
resolve(date);
}
}, 1000);
});
}
async function main() {
//Wait for 45th second
await setAlam(45);
console.log("Running tasks now");
}