承诺的确切行为是什么?

What's the exact behavior of the promises?

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

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



}

非常感谢您的协助。

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

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

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