【问题标题】:Promisify gcloud using Bluebird promise使用 Bluebird 承诺承诺 gcloud
【发布时间】:2016-07-27 20:40:14
【问题描述】:

我想承诺 gcloud 包中的所有方法,但我在这样做时出错了。

const Promise = require('bluebird');
const gcloud = Promise.promisifyAll(require('gcloud'));

//no problem when passing a callback into it
bucket.getFiles((err, files) => {
    console.log(files)
})

//Complain error -> bucket.getFilesAsync is not a function
bucket.getFilesAsync().then((files) => {
    console.log(files)
})

当我在promisifyAll 之后调用async 方法时,它会抱怨bucket.getFilesAsync is not a function,所以我尝试使用 ES6 承诺来承诺该方法。

const bucketFiles = new Promise((resolve, reject) => {
    bucket.getFiles((err, files) => {
        if (err) return reject(err);

        resolve(files);
    });
});

bucketFiles.then((files) => {
    console.log(files)
})

这种使用 ES6 方式的承诺是有效的,但我不想通过这样做来承诺每种方法。所以,我想让bluebird 为我承诺一切。

我可以知道如何使用 bluebird 承诺 gcloud 包吗?

【问题讨论】:

  • 这是什么bucket
  • 它是来自Google App Engine Cloud Storage的对象
  • 可能你需要Promise.promisifyAll(bucket);
  • 可能是Promise.promisifyAll(require('gcloud/lib/storage/bucket').prototype)?
  • 当你打电话给Promise.promisifyAll(bucket);时它正在工作,我可以知道为什么这是工作但不是Promise.promisifyAll(require('gcloud'))

标签: node.js google-app-engine promise bluebird es6-promise


【解决方案1】:

根据有关Promisification的文档:

通过遍历对象的属性来承诺整个对象 并在对象上创建每个函数的异步等效项 它的原型链。

那么,那么你promisify gcloud 对象,它与promisify bucket 无关,导致它的另一个类。

您可以为每个 Bucket 实例执行此操作

Promise.promisifyAll(bucket);

或者对 Bucket 的原型进行一次补丁以供应用

Promise.promisifyAll(require('gcloud/lib/storage/bucket').prototype);

【讨论】:

    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 2014-09-07
    • 2016-04-10
    • 1970-01-01
    • 2016-02-08
    • 2015-10-23
    相关资源
    最近更新 更多