Wednesday 15 November 2017

angular - How to create function that return promise from callback function

itemprop="text">



I use
javascript library that has
api.



libapi.callnetwork(arg1,callback(data){
//handle
data
}



then
i create service function to call api like
this



myFunction():Promise{

libapi.callnetwork(arg1,callback(data){
return new
Promise(resolve=>resolve(data));

})
}



myFunction
will get error because it must return promise or declare as void. How can i create
function that return promise from this api?


class="post-text" itemprop="text">
class="normal">Answer



The idea
is not to create and return the promise from inside the callback, but to create it in
the outside function (where you can return it) and only
resolve the promise from the
callback:



myFunction():Promise{

return new Promise(resolve => {
libapi.callnetwork(arg1,
callback(data){
resolve(data);
});

});

}


or
simply



myFunction():Promise{

return new Promise(resolve => {
libapi.callnetwork(arg1,
resolve);

});
}



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...