我已经成功地将函数“ notMyFunction”包装在一个Promise中,因此我可以像使用Promise一样使用“ notMyFunction”。像这样:


// I do not have access to "notMyFunction"
function notMyFunction(a, cb) {
    if (a === 'latest') {
        cb('123');
    } else {
        cb('error');
    }
}

// changing callback into a promise
function deploy(someVariable) {
    return new Promise((resolve, reject) => {
        notMyFunction(someVariable, resolve);
    });
}

// using callback as if it were a promise
deploy('latest').then((time) => {
    console.log(time)
}, (err) => {
    console.log(err)
})





我的问题是:当“ notMyFunction”实际上将两个参数传递给回调时,我该如何做同样的事情:




function notMyFunction(a, cb) {
    if (a === 'latest') {
        cb(null, '123');
    } else {
        cb('error', null);
    }
}
function deploy(someVariable) {
    return new Promise((resolve, reject) => {
        notMyFunction(someVariable, resolve);
    });
}
deploy('latest').then((time) => {
    // I need access to 123, not null
    console.log(time)
}, (err) => {
    console.log(err)
})

最佳答案

我认为您可能想研究“承诺化”的概念。

较新版本的Node.js具有util.promisify函数,可以处理此问题。 Axel博士有一个great write-up on util.promisify

如果您在浏览器中,则可能要考虑引入Promisify填充/填充,例如es6-promisify

以一致的方式在整个代码库中实现功能多样化将有助于您避免很多潜在的问题。

10-06 06:07