如何从回调函数创建返回承诺的函数

这个问题在这里已经有了答案:

  • 如何将现有的回调API转换为承诺? 17个答案

  • 这个想法并不是在回调中创建并返回promise,而是在外部函数中创建它(可以return它),并且只解析回调中的承诺:

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

    或干脆

    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/55515.html

    上一篇: How to create function that return promise from callback function

    下一篇: How to return a promise when writestream finishes?