我想使用promise,但我有一个回调API,格式如下:

1.DOM加载或其他一次性事件:

window.onload; // set to callback
...
window.onload = function() {

};

2.普通回调:

function request(onChangeHandler) {
    ...
}
request(function() {
    // change happened
    ...
});

3.节点样式回调(“nodeback”):

function getStuff(dat, callback) {
    ...
}
getStuff("dataParam", function(err, data) {
    ...
})

4.具有节点样式回调的整个库:

API;
API.one(function(err, data) {
    API.two(function(err, data2) {
        API.three(function(err, data3) {
            ...
        });
    });
});

我如何在promise中使用API,如何“promise”它?


当前回答

在内置promise和异步的节点v7.6+下:

// promisify.js
let promisify = fn => (...args) =>
    new Promise((resolve, reject) =>
        fn(...args, (err, result) => {
            if (err) return reject(err);
            return resolve(result);
        })
    );

module.exports = promisify;

如何使用:

let readdir = require('fs').readdir;
let promisify = require('./promisify');
let readdirP = promisify(readdir);

async function myAsyncFn(path) {
    let entries = await readdirP(path);
    return entries;
}

其他回答

也许已经回答了,但我通常是这样做的:

// given you've defined this `Future` fn somewhere:
const Future = fn => {return new Promise((r,t) => fn(r,t))}

// define an eventFn that takes a promise `resolver`
const eventFn = resolve => {
  // do event related closure actions here. When finally done, call `resolve()`
  something.oneventfired = e => {resolve(e)}
}

// invoke eventFn in an `async` workflowFn using `Future`
// to obtain a `promise` wrapper
const workflowFn = async () => {await Future(eventFn)}

特别是对于indexedDb事件包装器之类的东西,以简化使用。

或者你可能会发现未来的这种变化更具普遍性

class PromiseEx extends Promise {
  resolve(v,...a) {
    this.settled = true; this.settledValue = v;
    return(this.resolve_(v,...a))
  }
  reject(v,...a) {
    this.settled = false; this.settledValue = v;
    return(this.reject_(v,...a))
  }
  static Future(fn,...args) {
    let r,t,ft = new PromiseEx((r_,t_) => {r=r_;t=t_})
    ft.resolve_ = r; ft.reject_ = t; fn(ft,...args);
    return(ft)
  }
}

在内置promise和异步的节点v7.6+下:

// promisify.js
let promisify = fn => (...args) =>
    new Promise((resolve, reject) =>
        fn(...args, (err, result) => {
            if (err) return reject(err);
            return resolve(result);
        })
    );

module.exports = promisify;

如何使用:

let readdir = require('fs').readdir;
let promisify = require('./promisify');
let readdirP = promisify(readdir);

async function myAsyncFn(path) {
    let entries = await readdirP(path);
    return entries;
}

死灵一点,这个链接可能有用。。。。


太长,读不下去了看看这个答案末尾的代码片段示例


编写/转换可调用的函数

cb(错误,结果)或新Promise(…)格式


promiseToCB转换并导出先前编码为返回promise的现有函数cbToPromise转换并导出一个先前编码为调用最后一个参数的现有函数(error,result)如果包装函数提供了多个结果,则结果将是一个结果数组例如cb(undefined,path,stat)--->解析([path,stat])/cb(undefine,[path,stat])asPromise允许您编写一个新函数以返回promise,但它可以以任何方式调用asCallback允许您编写一个新函数来调用cb(err,result),但它可以通过任何方式调用

示例函数

每个样本取2个参数,并基于随机数解决/拒绝/错误。

arg2也可以用于强制通过或失败。(查找“-通过”或“-失败”)。

包装现有函数

将函数导出到当前的“this”(或使用promiseToCB(函数myFunc(){},newThis);)



    promiseToCB(function sampleFunc1(arg1,arg2) {
        console.log("deciding:",arg1,arg2);
        return new Promise(function(resolve,reject){
       
           const timer = setTimeout(function(){reject([arg1,arg2,"ouch"].join("-"));},5000);
           
           setTimeout(function(){
               if (arg2.endsWith("-pass") || (!arg2.endsWith("-fail") && Math.random()<0.5)) {
    
                   console.log("complete:",arg1,arg2);
                   clearTimeout(timer);
                   resolve([arg1,arg2,"all good"].join("-"));
               }
           },2000);
        
        });
    });
    
    cbToPromise('sampleFunc2',function someOtherName(arg1,arg2,cb) {
       console.log("deciding:",arg1,arg2);
       const timer = setTimeout(function(){cb([arg1,arg2,"ouch"].join("-"));},5000);
       
       setTimeout(function(){
           if (arg2.endsWith("-pass") || (!arg2.endsWith("-fail") && Math.random()<0.5)) {
               console.log("complete:",arg1,arg2);
               clearTimeout(timer);
               cb(undefined,[arg1,arg2,"all good"].join("-"));
           }
       },2000);
        
    },local);
    

或者编写嵌入包装器的新函数。

     function sampleFunc3(arg1,arg2) {return asPromise(arguments,function(resolve,reject){
       console.log("deciding:",arg1,arg2);
       const timer = setTimeout(function(){reject([arg1,arg2,"ouch"].join("-"));},5000);
       
       setTimeout(function(){
           if (arg2.endsWith("-pass") || (!arg2.endsWith("-fail") && Math.random()<0.5)) {
               console.log("complete:",arg1,arg2);
               clearTimeout(timer);
               resolve([arg1,arg2,"all good"].join("-"));
           }
       },2000);
        
    });}
    
    function sampleFunc4(arg1,arg2) {return asCallback(arguments,function(cb){
       console.log("deciding:",arg1,arg2);
       const timer = setTimeout(function(){cb([arg1,arg2,"ouch"].join("-"));},5000);
       
       setTimeout(function(){
           if (arg2.endsWith("-pass") || (!arg2.endsWith("-fail") && Math.random()<0.5)) {
               console.log("complete:",arg1,arg2);
               clearTimeout(timer);
               cb(undefined,[arg1,arg2,"all good"].join("-"));
           }
       },2000);
        
    });}

测试上述功能的scipt


    const local = {}; 
    promiseToCB(function sampleFunc1(arg1,arg2) {
        console.log("deciding:",arg1,arg2);
        return new Promise(function(resolve,reject){
       
           const timer = setTimeout(function(){reject([arg1,arg2,"ouch"].join("-"));},5000);
           
           setTimeout(function(){
               if (arg2.endsWith("-pass") || (!arg2.endsWith("-fail") && Math.random()<0.5)) {
    
                   console.log("complete:",arg1,arg2);
                   clearTimeout(timer);
                   resolve([arg1,arg2,"all good"].join("-"));
               }
           },2000);
        
        });
    });
    
    cbToPromise('sampleFunc2',function someOtherName(arg1,arg2,cb) {
       console.log("deciding:",arg1,arg2);
       const timer = setTimeout(function(){cb([arg1,arg2,"ouch"].join("-"));},5000);
       
       setTimeout(function(){
           if (arg2.endsWith("-pass") || (!arg2.endsWith("-fail") && Math.random()<0.5)) {
               console.log("complete:",arg1,arg2);
               clearTimeout(timer);
               cb(undefined,[arg1,arg2,"all good"].join("-"));
           }
       },2000);
        
    },local);
    
    function sampleFunc3(arg1,arg2) {return asPromise(arguments,function(resolve,reject){
       console.log("deciding:",arg1,arg2);
       const timer = setTimeout(function(){reject([arg1,arg2,"ouch"].join("-"));},5000);
       
       setTimeout(function(){
           if (arg2.endsWith("-pass") || (!arg2.endsWith("-fail") && Math.random()<0.5)) {
               console.log("complete:",arg1,arg2);
               clearTimeout(timer);
               resolve([arg1,arg2,"all good"].join("-"));
           }
       },2000);
        
    });}
    
    function sampleFunc4(arg1,arg2) {return asCallback(arguments,function(cb){
       console.log("deciding:",arg1,arg2);
       const timer = setTimeout(function(){cb([arg1,arg2,"ouch"].join("-"));},5000);
       
       setTimeout(function(){
           if (arg2.endsWith("-pass") || (!arg2.endsWith("-fail") && Math.random()<0.5)) {
               console.log("complete:",arg1,arg2);
               clearTimeout(timer);
               cb(undefined,[arg1,arg2,"all good"].join("-"));
           }
       },2000);
        
    });}
    
    const log=console.log.bind(console),info=console.info.bind(console),error=console.error.bind(console);
    
    sampleFunc1("sample1","promise").then (log).catch(error);
    local.sampleFunc2("sample2","promise").then (log).catch(error);
    sampleFunc3("sample3","promise").then (log).catch(error);
    sampleFunc4("sample4","promise").then (log).catch(error);

    sampleFunc1("sample1","callback",info);
    local.sampleFunc2("sample2","callback",info);
    sampleFunc3("sample3","callback",info);
    sampleFunc4("sample4","callback",info);
    
    sampleFunc1("sample1","promise-pass").then (log).catch(error);
    local.sampleFunc2("sample2","promise-pass").then (log).catch(error);
    sampleFunc3("sample3","promise-pass").then (log).catch(error);
    sampleFunc4("sample4","promise-pass").then (log).catch(error);

    sampleFunc1("sample1","callback-pass",info);
    local.sampleFunc2("sample2","callback-pass",info);
    sampleFunc3("sample3","callback-pass",info);
    sampleFunc4("sample4","callback-pass",info);
    
    
    sampleFunc1("sample1","promise-fail").then (log).catch(error);
    local.sampleFunc2("sample2","promise-fail").then (log).catch(error);
    sampleFunc3("sample3","promise-fail").then (log).catch(error);
    sampleFunc4("sample4","promise-fail").then (log).catch(error);
    
    sampleFunc1("sample1","callback-fail",info);
    local.sampleFunc2("sample2","callback-fail",info);
    sampleFunc3("sample3","callback-fail",info);
    sampleFunc4("sample4","callback-fail",info);
 

var cpArgs=Array.prototype.slice.call.bind(Array.proto原型.slice);函数promiseToCB(nm,fn,THIS){如果(nm类型==='功能'){这=fn;fn=纳米;nm=fn.name;}此=此||此;const func=函数(){let args=cpArgs(参数);if(参数类型[args.length-1]=='函数'){const cb=args.pop();return fn.apply(THIS,args).then(函数(r){cb(未定义,r);}).捕获(cb);}其他{return fn.apply(THIS,args);}};Object.defineProperty(func,'name',{value:nm,enumerable:false,可配置:true});如果(此[nm])删除此[nm];Object.defineProperty(THIS,nm,{value:func,enumerable:false,可配置:true});返回函数;}函数cbToPromise(nm,fn,THIS){如果(nm类型==='功能'){这=fn;fn=纳米;nm=fn.name;}此=此||此;const func=函数(){let args=cpArgs(参数);if(参数类型[args.length-1]=='函数'){return fn.apply(THIS,args);}其他{return new Promise(函数(解析,拒绝){args.push(函数(错误,结果){if(error)返回reject(err);if(arguments.length==2){返回解析(result);}返回解析(cpArgs(arguments,1));});fn.apply(此,参数);});}};Object.defineProperty(func,'name',{value:nm,enumerable:false,可配置:true});如果(此[nm])删除此[nm];Object.defineProperty(THIS,nm,{value:func,enumerable:false,可配置:true});返回函数;}函数作为Promise(args,解析器,no_err){常量cb=参数[args.length-1],promise=新promise(解析器);return(cb类型=='函数')?promise.then(函数(结果){return cb(no-err,结果)}).catch(cb):promise;}函数作为回调(args,wrap,no_err){常量cb=参数[args.length-1],promise=新promise(函数解析器(resolve,reject){返回换行(函数(错误,结果){if(error)返回reject(err);解决(结果);});});return(cb类型=='函数')?promise.then(函数(结果){return cb(no-err,结果)}).catch(cb):promise;}函数cbPromiseTest(){/*全局样本Func1,样本Func2*/常量local={};promiseToCB(函数sampleFunc1(arg1,arg2){console.log(“决定:”,arg1,arg2);return new Promise(函数(解析,拒绝){const timer=setTimeout(函数(){reject([arg1,arg2,“ouch”].jjoin(“-”);},5000);setTimeout(函数){if(arg2.endsWith(“-pass”)||(!arg2.ends With(”-ffail“)&&Math.random()<0.5)){console.log(“完成:”,arg1,arg2);clearTimeout(计时器);解析([arg1,arg2,“一切正常”].join(“-”));}},2000);});});cbToPromise('sampleFunc2',函数someOtherName(arg1,arg2,cb){console.log(“决定:”,arg1,arg2);const timer=setTimeout(函数){cb([arg1,arg2,“ouch”].jjoin(“-”);},5000);setTimeout(函数){if(arg2.endsWith(“-pass”)||(!arg2.ends With(”-ffail“)&&Math.random()<0.5)){console.log(“完成:”,arg1,arg2);clearTimeout(计时器);cb(未定义,[arg1,arg2,“all good”]。join(“-”));}},2000);},本地);函数sampleFunc3(arg1,arg2){return asPromise(参数,函数(解析,拒绝){console.log(“决定:”,arg1,arg2);const timer=setTimeout(函数(){reject([arg1,arg2,“ouch”].jjoin(“-”);},5000);setTimeout(函数){if(arg2.endsWith(“-pass”)||(!arg2.ends With(”-ffail“)&&Math.random()<0.5)){console.log(“完成:”,arg1,arg2);clearTimeout(计时器);解析([arg1,arg2,“一切正常”].join(“-”));}},2000);});}函数sampleFunc4(arg1,arg2){return asCallback(参数,函数(cb){console.log(“决定:”,arg1,arg2);const timer=setTimeout(函数){cb([arg1,arg2,“ouch”].jjoin(“-”);},5000);setTimeout(函数){if(arg2.endsWith(“-pass”)||(!arg2.ends With(”-ffail“)&&Math.random()<0.5)){console.log(“完成:”,arg1,arg2);clearTimeout(计时器);cb(未定义,[arg1,arg2,“all good”]。join(“-”));}},2000);});}const log=console.log.bind(控制台),info=console.info.bind(控制台,error=console.error.bind);sampleFunc1(“sample1”,“promise”).then(log).catch(error);local.sampleFunc2(“sample2”,“promise”).then(log).catch(error);sampleFunc3(“sample3”,“promise”).then(log).catch(error);sampleFunc4(“sample4”,“promise”).then(log).catch(error);sampleFunc1(“sample1”,“回调”,信息);local.sampleFunc2(“sample2”,“回调”,信息);sampleFunc3(“sample3”,“回调”,信息);sampleFunc4(“sample4”,“回调”,信息);sampleFunc1(“sample1”,“promise pass”).then(log).catch(error);local.sampleFunc2(“sample2”,“pr”

承诺总是有决心和拒绝。当您编写异步包装器时,只需调用resolve即可。

您可以为几乎所有接受回调的函数编写包装函数,如下所示:

const myAsyncWrapper = (...params) =>
  new Promise((resolve, reject) => 
    someFunctionWithCallback(...params, (error, response) =>
      error ? reject(error) : resolve(response)
    )
  );

您可以进一步编写回调到promise的转换函数:

const promisify =
  (functionWithCallback) =>
  (...params) =>
    new Promise((resolve, reject) =>
      functionWithCallback(...params, (error, response) =>
        error ? reject(error) : resolve(response)
      )
    );

当使用较旧的库或SDK时,包装函数的概念尤其有用。例如,考虑FacebookGraph API的JavaScriptSDK,它使用类似的回调结构来发出API请求。

FB.api(apiURL, options, function (request) {
  if (request.error || !request) return;
  // handle request
});

在现代应用程序中,使用基于承诺的API更有用。如果您只使用一个函数一次或两次,则最好单独给出响应:

// in an async function
const response = await new Promise((resolve, reject) =>
  FB.api(apiURL, (res) => (res?.error ? reject(res?.error) : resolve(res)))
);

如果经常使用该函数,可以使用相同的包装器概念来编写如下函数:

const apiWrapper = (...params) =>
  new Promise((resolve, reject) => 
    FB.api(...params, (res) => (res?.error ? reject(res?.error) : resolve(res)))
  );

虽然promisifier有时很好,但它们不适用于这样的特定实例。在这种情况下,在Github上寻找一个现代的包装器,或者像这样编写自己的包装器。

您可以在NodeJS中使用JavaScript本机承诺。

My Cloud 9代码链接:https://ide.c9.io/adx2803/native-promises-in-node

/**
* Created by dixit-lab on 20/6/16.
*/

var express = require('express');
var request = require('request');   //Simplified HTTP request client.


var app = express();

function promisify(url) {
    return new Promise(function (resolve, reject) {
        request.get(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body);
            }
            else {
                reject(error);
            }
        })
    });
}

//get all the albums of a user who have posted post 100
app.get('/listAlbums', function (req, res) {
    //get the post with post id 100
    promisify('http://jsonplaceholder.typicode.com/posts/100').then(function (result) {
        var obj = JSON.parse(result);
        return promisify('http://jsonplaceholder.typicode.com/users/' + obj.userId + '/albums')
    })
    .catch(function (e) {
        console.log(e);
    })
    .then(function (result) {
        res.end(result);
    })
})

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port

    console.log("Example app listening at http://%s:%s", host, port)
})

//run webservice on browser : http://localhost:8081/listAlbums