如何从库创建承诺 [英] How to create promises from library

查看:48
本文介绍了如何从库创建承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此感到困惑,因为到目前为止我找到的每个教程都假设我可以编辑库代码,或者库只有回调或回调作为最后一个参数.

I am confused on this one because every tutorial I have found so far assumes I can edit the library code, or that the library only has call backs or the call back as the last parameter.

我使用的库的每个功能都设置如下<代码>功能(successCallBack(结果),FailCallBack(误差),选项)

The library I am using has every function set up like function(successCallBack(result), FailCallBack(error),options)

所以在每种情况下,我最终都会使用类似的代码

So in each instance, I end up using code like

var options={stuff1:1, stuff2:2};

doStuff(success,failure,options);

function success(result){
    //handle, usually with another call to a similar function, chaining callbacks together
};

function failure(error){
     //handle error
};

当我只能控制调用以及成功和失败时,如何将这些转换为承诺?

How do I convert these into promises when I only have control of the call, and the success and failures?

此外,作为奖励,链正在访问它们外部的变量.

Also, as a bonus, the chains are accessing variables outside them.

var options={stuff1:1, stuff2:2};

doStuff(success,failure,options);

function success(result){
    var options2={stuff1:1, stuff2:2};
    doStuff2(function(result2){
                processStuff(result1, result2);
            },function(error){
                 //handle error
            },options2)
};

function failure(error){
     //handle error
};

function processSuff(result1,result2){
    //do things to results
}

谢谢

推荐答案

您可以使用以下函数.它接受一个函数来承诺和选项,并返回承诺:

You could use the following function. It accepts a function to promisify and options, and returns promise:

let promisify = (fn, opts) => {
  return new Promise((resolve, reject) => {
    fn(resolve, reject, opts);
  });
}

可以如下使用:

promisify(doStuff, options)
  .then(data => console.log('Success call', data))
  .catch(err => console.log('Error', err));

这篇关于如何从库创建承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆