从函数返回承诺 [英] Return promise from the function

查看:57
本文介绍了从函数返回承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

返回 this.db.find

return this.db.find

哪个find函数是一个promise

which find function is a promise

然后链的结尾返回

返回 this.db.post(person)

return this.db.post(person)

即使是 post 功能也是一种承诺.

even post function is a promise.

这里,我有三个问题

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

1) When this function executes, what would return?

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

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

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

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

推荐答案

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

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=preview for the working version; open the console to see the results!):

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

对于您的问题:

  1. 您将 Promise 与所有链接的 then 函数一起返回.如果在返回的 Promise 中添加另一个 then,它将被添加到链的末尾.这就是您在执行 test().then(...) 时所看到的.
  2. Promise 会告诉您它将在某个时间点执行,但不会告诉您何时执行.只要 Promise 解决,then 链就会执行.您可以在 returnPromise 中更详细地了解这一点.这里我们返回一个新的 Promise.Promise 的主体在完成时调用 resolve 方法(在这种情况下是立即),触发 Promise 解析并执行链接到 Promise 的所有 then 方法.通常 Promise 不会立即解析,而是会先执行异步任务(例如从服务器检索数据).
  3. 这实际上取决于应用程序的类型和您正在寻找的内容.只要责任​​明确,你目前的方法本身并不坏.
  1. You return the Promise together with all the chained then functions. If you add another then to 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 resolve method when it is done (in this case that is instantly), triggering the Promise to resolve and execute all then methods 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.

这篇关于从函数返回承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆