Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  197] [ 1]  / answers: 1 / hits: 92390  / 7 Years ago, wed, may 10, 2017, 12:00:00

I've a function like this:



function top() {

//promise1
ParentPromise({
...some code here...
}).then(function() {


//promise2
ChildPromise({
..some code here...
}).then(function(response) {
var result = response.result.items;

});

});

};


and i need to return result value in this way:



var myresult = start();


How i can do that? THX


More From » promise

 Answers
48

The definition of promises is that you cannot literally assign result to myresult. However, you can make myresult a promise that resolves directly to result for the caller, however many promises were used to get that. The basic idea is that inside of each function in your above block, you should be returning the next Promise in the chain. eg:



function top() {

//promise1
return ParentPromise({
...some code here...
}).then(function() {


//promise2
return ChildPromise({
..some code here...
}).then(function(response) {
var result = response.result.items;
return result;

});

});

};


In the end, the code calling top() won't know or care that 1, 2, or 12 chained promises were used to get result. It will also be able to register an error callback in case any of those promises failed.


[#57833] Sunday, May 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;