How to create function that return promise from callback function

This question already has an answer here:

  • How do I convert an existing callback API to promises? 17 answers

  • 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);
      });
    }
    

    香草,抢解析功能

    let myFunction = () => {
        let resolve;
        let promise = new Promise(r => resolve = r);
        libapi.callnetwork(arg1, resolve);
        return promise;
    };
    

    myFunction():Promise<any>{
      let resolveFn = (data) => data;
      libapi.callnetwork(arg1, resolveFn);
      return new Promise(resolveFn);
    }
    
    链接地址: http://www.djcxy.com/p/55516.html

    上一篇: AngularJS承诺不使用FileReader解析文件

    下一篇: 如何从回调函数创建返回承诺的函数