typescript 从函数返回承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40735418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:01:45  来源:igfitidea点击:

Return promise from the function

javascriptangulartypescriptpromisees6-promise

提问by Shabbir

I have a shallow understanding of JavaScript Promise and promise chain. Say, I have a method as shown below. It's written is TypeScript, but could be modified to match JavaScript ES6

我对 JavaScript Promise 和 promise 链的理解比较浅。说,我有一个如下所示的方法。它是用 TypeScript 编写的,但可以修改以匹配 JavaScript ES6

private InsertPersonInDB(p : Person) {    
     return this.db.find({                              //<- would this return?
                selector: {objType: 'Person'},
                fields: ['_id'],
                sort: ['_id']
            }).then( result => {                         
                let allpersondIds : string[] = [];
                (result.docs).forEach(rec => {
                    allpersondIds.push(rec._id);
                });
                return allpersondIds;                
            }).then ( allpersonIdsInDB => {                
                var id = this.getIdfromPersonName(person.personName, allpersonIdsInDB);
                person._id = id;
                return this.db.post(person)            //<- or would this return?
            }
}

//Calling function
for(let person of this.persons) {
    InsertPersonInDB(person).then(result => {
        console.log(result)
        //Some UI updates       
    }).catch(err => {
        console.log(err)
        //Some UI updates notifying user about failure  
    }); 
}

Here, I have two return, first is

在这里,我有两个回报,第一个是

return this.db.find

返回 this.db.find

which findfunction is a promise

哪个find函数是一个承诺

and end of the then chain returns

然后链的末端返回

return this.db.post(person)

返回 this.db.post(person)

even postfunction is a promise.

甚至post功能也是一种承诺。

Here, I have three questions

在这里,我有三个问题

1) When this function executes, what would return?

1)当这个函数执行时,会返回什么?

2) If the function immediately returns the promise, when would the chain thensexecute?

2)如果函数立即返回promise,那么链什么时候执行?

2) What are better approaches to refactored the promise chain in a layered application. E.g. Few chain thenneeds to be executed in the service, other needs to be executed in UI, how do I structure my promises code?

2)在分层应用程序中重构承诺链的更好方法是什么。如少数链需要在服务,其他需要在UI执行,我该如何构建我的诺言代码被执行?

回答by Sjoerd

First of all, I think you can easily test our your questions by just making some small examples for yourself. When I am unclear about how things work, I find it very useful to create a small example to just try out and see what happens. Lets do that for this question as well (see also https://plnkr.co/edit/K18o4Lp2jtUincjyG5wi?p=previewfor the working version; open the console to see the results!):

首先,我认为您可以通过为自己制作一些小示例来轻松测试我们的问题。当我不清楚事情是如何运作时,我发现创建一个小例子来尝试看看会发生什么非常有用。对于这个问题,我们也可以这样做(工作版本另见https://plnkr.co/edit/K18o4Lp2jtUincjyG5wi?p=preview;打开控制台查看结果!):

function test() {
  return returnPromise().then((value) => {
    console.log('1st then, inside test(): ' + value);
    return 'Hello';
  }).then((value) => {
    console.log('2nd then, inside test(): ' + value);
    return 'world';
  });
}

function returnPromise() {
  return new Promise(function(resolve, reject) {
    resolve('start of new Promise');
  });
}

test().then((value) => {
  console.log('3rd then, after calling test: ' + value);
});

For your questions:

对于您的问题:

  1. You return the Promise together with all the chained thenfunctions. If you add another thento the returned Promise, it will be added at the end of the chain. That is what you see when we are doing test().then(...).
  2. A Promise tells you that it will execute at some point in time, without telling you when. The then chain will execute whenever the Promise resolves. You can see that in more detail in returnPromise. Here we return a new Promise. The body of the Promise calls the resolvemethod when it is done (in this case that is instantly), triggering the Promise to resolve and execute all thenmethods chained to the Promise. Usually the Promise won't resolve instantly, but will perform an async task (e.g. retrieving data from a server) first.
  3. That really depends on the type of application and what you are looking for. Your current approach is not bad in itself, as long as the responsibilities are clearly defined.
  1. 您将 Promise 与所有链接的then函数一起返回。如果then在返回的 Promise 中添加另一个,它将被添加到链的末尾。这就是你在我们做的时候看到的test().then(...)
  2. Promise 会告诉您它将在某个时间点执行,但不会告诉您何时执行。只要 Promise 解决,then 链就会执行。您可以在 中更详细地了解这一点returnPromise。这里我们返回一个新的 Promise。Promise 的主体在resolve完成时调用该方法(在这种情况下是立即),触发 Promise 解析并执行then链接到 Promise 的所有方法。通常 Promise 不会立即解析,而是首先执行异步任务(例如从服务器检索数据)。
  3. 这实际上取决于应用程序的类型和您正在寻找的内容。只要责任​​明确,你目前的方法本身并不坏。

回答by Günter Z?chbauer

1) A promise that resolves to the result of the db.post(person)request.

1) 解析db.post(person)请求结果的承诺。

2) The callback passed to then(...)is executed when the db.post()call returns a response or throws an exception.

2) 传递给的回调then(...)db.post()调用返回响应或抛出异常时执行。

3) No idea. I don't think there is a general answer. It depends on what API you want to provide to the users of this service.

3)不知道。我不认为有一个普遍的答案。这取决于您要向此服务的用户提供什么 API。