javascript - Bluebird 递归 promise 未得到解决/履行

标签 javascript node.js promise bluebird

使用 BlueBird promise ,我尝试将 getCredentials 变成一个将作为 getCredentials.then(function() { do this and that } ); 工作的 promise 。不确定我做错了什么,因为当我在 writeToFile 中解析时, promise 不被视为已解决/已完成。

function getPassword(user) {
    return new Promise(function(resolve, reject) {
    read({prompt: "Password: ", silent: true, replace: "*" }, function (er, pass) {
        rest.postJson(URL, payload(user, pass))
            .on('fail', httpFail)
            .on('error', conError)
            .on('success', writeToFile);
    });
    });
}

function getCredentials() {
    return new Promise(function(resolve, reject) {
    read({prompt: "Username: "}, function (er, user) {
        getPassword(user);
    });
    });
}

function writeToFile(data, response) {
     return new Promise(function(resolve, reject) {
    tokenFile = 'gulp/util/token-file.json'
    token = {
        id: data.access.token.id,
        expires: data.access.token.expires
    }
    token = JSON.stringify(token);
    fs.writeFile(tokenFile, token, function(err) {
        if (err) throw err;
        console.log("Token was successfully retrieved and written to " .cyan +
            tokenFile .cyan + "." .cyan);
    resolve();
    });
     });
}

module.exports = getCredentials;

最佳答案

Not sure what I am doing wrong, because when I resolve in writeToFile the promise is not counted as resolved/fullfilled

好吧,您从 writeToFile 返回的 promise 已实现。
但是从 getPasswordgetCredentials 返回的 promise 永远不会 - 您没有调用它们 resolve 函数。 Promise 构造函数不会神奇地知道其中使用的异步回调,或者其中会创建 Promise。

您无法从异步回调中返回任何内容,从那里发出结果信号的唯一方法是调用另一个(回调)函数。在 Promise 构造函数的解析器内部,这将是 resolvereject 回调。

您可能想看看my rules for promise development 。我们几乎从不使用 Promise 构造函数,只是为了 promisify在尽可能低的水平。在你的情况下,那就是

function readAsync(options) {
    return new Promise(function(resolve, reject) {
        read(options, function (err, pass) {
            if (err) reject(err);
            else resolve(pass);
        }
    });
}
function postAsync(url, payload) {
    return new Promise(function(resolve, reject) {
        rest.postJson(url, payload)
        .on('fail', reject)
        .on('error', reject)
        .on('success', resolve);
    });
}

虽然使用 Bluebird 我们可以简化第一个

var readAsync = Promise.promisify(read);

和类似用途

var writeFileAsync = Promise.promisify(fs.writeFile, fs);

现在我们有了这些 Promise 返回函数,我们可以应用其余规则并将它们组合在一起,而无需再使用 Promise 构造函数:

function getPassword(user) {
    return readAsync({prompt: "Password: ", silent: true, replace: "*" })
    .then(function(pass) {
        return postAsync(URL, payload(user, pass))
    });
}

function getCredentials() {
    return readAsync({prompt: "Username: "}).then(getPassword);
}

function writeToFile(data, response) {
    var tokenFile = 'gulp/util/token-file.json';
    var token = JSON.stringify({
        id: data.access.token.id,
        expires: data.access.token.expires
    });
    return writeFileAsync(tokenFile, token).then(function() {
        console.log("Token was successfully retrieved and written to " .cyan +
                    tokenFile .cyan + "." .cyan);
    });
}

module.exports = getCredentials;

关于javascript - Bluebird 递归 promise 未得到解决/履行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28958458/

相关文章:

javascript - React-native:textAlign: 'right' 样式不正确

javascript - Node js 中的 date() 函数是提供服务器端日期还是客户端日期?

node.js - Firebase Cloud Functions 中抛出未处理的错误

Javascript 等待在异步函数中不被尊重

javascript - 完整日历获取当前日期

javascript - Swiper - 未找到依赖项 Typescript,ionic-vue

node.js - AWS Lambda : How to store secret to external API?

javascript初始化对象(和dom)

javascript - 如何正确使用promise的resolve和reject

javascript - 将 jQuery.Deferred 对象传递给 deferred.resolve 时,jQuery.Deferred 是否存在错误?