我对 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?
推荐答案首先,我认为您可以通过为自己制作一些小示例来轻松测试我们的问题.当我不清楚事情是如何运作时,我发现创建一个小例子来尝试看看会发生什么非常有用.让我们对这个问题也这样做(另见 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 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); });对于您的问题:
更多推荐
从函数返回承诺
发布评论