1

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<any>{
  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?

medici
  • 199
  • 1
  • 4
  • 11

3 Answers3

17

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<any>{
  return new Promise(resolve => {
    libapi.callnetwork(arg1, callback(data){
      resolve(data);
    });
  });
}

or simply

myFunction():Promise<any>{
  return new Promise(resolve => {
    libapi.callnetwork(arg1, resolve);
  });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Vanilla, grab the resolve function

let myFunction = () => {
    let resolve;
    let promise = new Promise(r => resolve = r);
    libapi.callnetwork(arg1, resolve);
    return promise;
};
Paul S.
  • 64,864
  • 9
  • 122
  • 138
-1
myFunction():Promise<any>{
  let resolveFn = (data) => data;
  libapi.callnetwork(arg1, resolveFn);
  return new Promise(resolveFn);
}
Meir
  • 14,081
  • 4
  • 39
  • 47