【问题标题】:Swap order of arguments to "then" with Bluebird / NodeJS Promises使用 Bluebird / NodeJS Promises 将参数顺序交换为“then”
【发布时间】:2016-09-25 23:19:13
【问题描述】:

我有一个从服务器异步获取值的函数:

var request = require('request');
Promise.promisifyAll(request);
function getValue(){
    return request.getAsync('http://www.google.com')
        .then(function(resp){ return resp.body; })
        .catch(function(err){ thow err; });
}

我想把这个值转储到一个文件中:

var fs = require('fs');
Promise.promisifyAll(fs);
getValue().then(fs.writeFileAsync, "file.html");

问题是fs.writeFileAsync希望参数一是文件,参数二是数据,但getValue()返回数据。这是错误的说:

Unhandled rejection Error: ENAMETOOLONG: name too long, open '<html....'
    at Error (native)

我现在可以通过编写一个辅助函数来交换参数来规避这个问题:

function myWriteFile(data, fileName) {
    return fs.writeFileAsync(fileName, data);
}

虽然如果可以在不编写首选辅助函数的情况下解决此问题,因为我预计会出现很多类似的问题,并且不想用 50 个辅助函数使我的代码混乱。我也觉得将数据从 Promise 传递给 writeFile 可能是一个非常常见的用例。

【问题讨论】:

  • then(fs.writeFileAsync, "file.html") 并不是你想的那样。
  • 您不会将函数参数直接传递给.then(),因此您的想法在这里完全有缺陷。 .then() 接受一两个函数引用,这就是它所接受的全部。第一个函数引用是解析处理程序,第二个是拒绝处理程序。
  • 我不熟悉使用 promises(第一个使用它们的项目),这是有道理的,尽管它没有解释我能够通过传递参数来修复的早期错误。我有一个波浪号扩展辅助函数,它返回一个承诺。然后我得到了代码tilde(fileName).then(fs.readFileAsync).then(function(data){console.log(data);})——它返回了一个缓冲区,而不是一个字符串。我用tilde(fileName).then(fs.readFileAsync, "utf8").then(function(data){console.log(data);}) 替换了它,它返回了一个字符串
  • 做了一些 git log 研究,看起来我以前有 fs.readFileAsync(fileName, "utf8"),但是当我添加波浪号扩展库时,我不正确地将它转换为 tilde(fileName).then(fs.readFileAsync, "utf8")。我测试过,它再次返回一个缓冲区而不是一个字符串。我的代码没有中断的唯一原因是之后的代码显然支持缓冲区。

标签: javascript node.js promise bluebird fs


【解决方案1】:

.then() 函数的第二个参数是错误回调,而不是参数。您的代码根本不起作用。

相反,您可以使用.bind 预绑定参数:

getValue().then(fs.writeFileAsync.bind(null, "file.html"));

注意.bind()的第一个参数是this参数,没关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-15
    • 2015-11-14
    • 2015-12-30
    • 1970-01-01
    • 2015-01-29
    • 2021-09-10
    相关资源
    最近更新 更多