Typescript 如何在Async/await中转换函数?
我正在尝试以异步/等待方式转换此函数:Typescript 如何在Async/await中转换函数?,typescript,async-await,nativescript,Typescript,Async Await,Nativescript,我正在尝试以异步/等待方式转换此函数: finddevice(s: any) { if (s !== '') { for (let i = 1; i < 255; i++) { this.ws.ping(s + '.' + i).subscribe(res => { console.log('res', res) if (res
finddevice(s: any) {
if (s !== '') {
for (let i = 1; i < 255; i++) {
this.ws.ping(s + '.' + i).subscribe(res => {
console.log('res', res)
if (res) {
try { throw i }
catch (ii) {
let myipfind = s + '.' + ii;
this.myipdevice = myipfind;
}
}
},(error) => {
console.log('got error from finddevice', error);
})
}
}
}
finddevice(s:any){
如果(s!=''){
for(设i=1;i<255;i++){
this.ws.ping(s+'.+i).subscribe(res=>{
console.log('res',res)
如果(res){
试试{扔我}
捕获(二){
设myipfind=s+'.+ii;
this.myipdevice=myipfind;
}
}
},(错误)=>{
log('从finddevice获取错误',错误);
})
}
}
}
我跟随并试图改变我的功能。然而,什么都不会发生,错误的答案不会停止
promiseFun(){
this.s = `${this.myip & 0xFF}.${(this.myip >> 8) & 0xFF}.${(this.myip >> 16) & 0xFF}`
return new Promise((resolve,reject)=>{
if (s !== '') {
for (let i = 1; i < 255; i++) {
this.ws.ping(s + '.' + i).subscribe(res => {
if (res) {
try { throw i }
catch (ii) {
let myipfind = s + '.' + ii;
this.myipdevice = myipfind;
}
}
},(error) => {
console.log('got error from finddevice', error);
})
}
}
}
setTimeout(()=>{
resolve("Resolved");
},2000);
})
}
async makeCall() {
try {
let successData= await this.promiseFun();
console.log(successData);
} catch (error) {
console.log(error);
}
}
promiseFun(){
this.s=`${this.myip&0xFF}.${(this.myip>>8)&0xFF}.${(this.myip>>16)&0xFF}`
返回新承诺((解决、拒绝)=>{
如果(s!=''){
for(设i=1;i<255;i++){
this.ws.ping(s+'.+i).subscribe(res=>{
如果(res){
试试{扔我}
捕获(二){
设myipfind=s+'.+ii;
this.myipdevice=myipfind;
}
}
},(错误)=>{
log('从finddevice获取错误',错误);
})
}
}
}
设置超时(()=>{
决定(“已决定”);
},2000);
})
}
异步makeCall(){
试一试{
让successData=等待此消息。promiseFun();
console.log(successData);
}捕获(错误){
console.log(错误);
}
}
找到正确答案,但错误答案仍不会停止
你知道如何阻止错误的答案吗
我正在尝试以异步/等待方式转换此函数:
finddevice(s: any) {
if (s !== '') {
for (let i = 1; i < 255; i++) {
this.ws.ping(s + '.' + i).subscribe(res => {
console.log('res', res)
if (res) {
try { throw i }
catch (ii) {
let myipfind = s + '.' + ii;
this.myipdevice = myipfind;
}
}
},(error) => {
console.log('got error from finddevice', error);
})
}
}
}
只需使用toPromise
,您就可以等待
await this.ws.ping(s + '.' + i).toPromise();
在运行下一次ping之前,您必须等待结果,只有在上一次ping失败时才执行下一次ping。如何执行?你能修改我的代码吗?