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
Not quite sure if this would work with native JS promises, but in
PromiseKit
(swift.. i know, but i'm pretty sure this should work) i'm used to returning the second promise, and chain it like this:Or in ES6 / lambda notation;
The challenge here is that you're trying to use asynchronous code in a synchronous way. You will need to change the way you think when working with asynchronous code.
One way to solve this is by having top() return ParentPromise, and then set the variable myresult using the .then() of the return of that promise.
However, for this to work, you'll need to add code to resolve your promise:
Run the following code, expanding to fit your specific circumstances. Note how it illustrates returning Promises, adding logic at various points along the way, before, during and after handling various pending logic.
The definition of promises is that you cannot literally assign
result
tomyresult
. However, you can makemyresult
a promise that resolves directly toresult
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 bereturn
ing the next Promise in the chain. eg:In the end, the code calling
top()
won't know or care that 1, 2, or 12 chained promises were used to getresult
. It will also be able to register an error callback in case any of those promises failed.