简体   繁体   English

如何从Promise内部将函数作为预订返回

[英]How to return a function as subscription from inside of a promise

I've been returning requests from my functions like this: 我一直从这样的函数返回请求:

makeConnection(data: any) {
    console.log('makeConnection');
    return this.api.get(data.url, data.dataToSend);
  }

So I can subscribe like this: makeConnection.subscribe(); 所以我可以这样订阅: makeConnection.subscribe();

Now I need to check if a variable named urls is set before making an API call So I thought of making a promised function like this 现在,我需要在进行API调用之前检查是否设置了名为urls的变量,所以我想到了制作这样的承诺函数

checkIfUrlsPresent():Promise<boolean> {
    return new Promise((resolve, reject) => {
      if(this.urls) {
        resolve(true);
        return;
      }
      this.api.get('/service', null).subscribe((response) => {
        console.log(response);
        this.urls = response.value.urls;
        resolve(true);        
      });
    });
  }

And now my service functions look like this: 现在,我的服务功能如下所示:

requestService(data) {
 this.checkIfUrlsPresent().then(() => {
      console.log('requestService');
      let dataToSend = this.api.createFormData(data);
      return this.api.post('/service/request/', dataToSend);
    })    
}

But now I won't be able to subscribe to my function like requestService(data).subscribe() So my question is how to keep my present flow working while adding this promise or is there any way to check that my variable is set before making a call while keeping this flow working. 但是现在我将无法订阅诸如requestService(data).subscribe()类的函数,所以我的问题是如何在添加此requestService(data).subscribe()同时保持当前流程正常运行,或者是否有任何方法可以检查之前是否设置了变量在保持此流程正常工作的同时进行通话。

Note: The problem is that I'm making all my api calls from one files and there are too many functions that calls these APIs so I need this way so that I won't need to make changes in all my pages to check if url is present. 注意:问题是我正在从一个文件进行所有api调用,并且调用这些API的函数过多,因此我需要这种方式,这样就无需在所有页面中进行更改即可检查网址存在。

Almost there. 快好了。 need to return the promise inside the function as well 还需要在函数内部返回promise

requestService(data) {
    return this.checkIfUrlsPresent().then(() => { // return the promise
      console.log('requestService');
      let dataToSend = this.api.createFormData(data);
      return this.api.post('/service/request/', dataToSend);
    })    
}

Have requestService return the chained promises, and call .then on it: requestService返回链接的诺言,然后调用.then

requestService(data) {
  return this.checkIfUrlsPresent().then(() => {
    console.log('requestService');
    let dataToSend = this.api.createFormData(data);
    return this.api.post('/service/request/', dataToSend);
  })
}

// ..

instance.requestService(someData)
  .then(service => service.subscribe())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM