如何在异步/等待中转换函数?

时间:2019-02-12 15:06:55

标签: 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) {
                        try { throw i }
                        catch (ii) {
                            let myipfind = s + '.' + ii;
                            this.myipdevice = myipfind;

                        }
                    }
                },(error) => {
                    console.log('got error from finddevice', error);
                })
            }
        }
    }

我遵循Async/await并尝试更改我的功能。但是,什么也没有发生,错误的答案不会停止。

   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);
        }
      }

可以得到正确的答案,但错误的答案仍然不会停止。

有什么主意如何阻止错误答案吗?

1 个答案:

答案 0 :(得分:0)

  

我正在尝试在异步/等待中转换此功能:

只需使用class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { //dummyhead doesn't store anything useful ListNode dummyhead = new ListNode(0); ListNode curr = dummyhead.next; while(l1 != null && l2 != null) { if(l1.val < l2.val) { //System.out.println("!!!"); curr = l1; curr = curr.next; l1 = l1.next; } else { curr = l2; //System.out.println(curr.val); System.out.println(dummyhead.next); curr = curr.next; l2 = l2.next; } } return dummyhead.next; } } ,您就可以等待例如

toPromise