【问题标题】:What's the exact behavior of the promises?承诺的确切行为是什么?
【发布时间】:2017-05-01 01:49:59
【问题描述】:

我是 Web 开发新手,最近我开始面临承诺,所以在下面的代码中,结果会在几毫秒后得到解决,但如果我刷新浏览器并立即单击按钮,我会得到一个“未定义”,那么它应该是这样吗?还是承诺通常必须等待并且不给出任何结果(甚至未定义),除非它已解决或失败或我的实现错误?

import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'my-app',
  template: `<button (click)="showMyId()">Next</button>
  <h1>S {{myId}} </h1>`,
})
export class AppComponent implements OnInit { 
  thepeer: any;
  myId: any;

  ngOnInit(){
    this.thepeer = new Peer({key: '1h907r5xnvims4i'});
    this.showMyId();
  }

  showMyId(){
    this.getMyId().then((id)=>{
      this.myId = id;
      console.log(this.myId);
    })
  }

  getMyId(){
    return new Promise((resolve, reject)=>{
      resolve(this.thepeer.id);
    })
  }



}

非常感谢您的帮助。

【问题讨论】:

    标签: javascript angular peerjs


    【解决方案1】:

    您必须等待open 事件触发后才能使用 ID:

    getMyId(){
        return new Promise((resolve, reject)=>{
          this.thepeer.on('open', (id) => {
              resolve(this.thepeer.id);
          });
       })
    }
    

    查看文档:http://peerjs.com/docs/#start

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 2017-10-09
      • 2021-02-11
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      相关资源
      最近更新 更多