如何使用蓝鸟地图和返回对象 [英] How to use bluebird map and return object

查看:107
本文介绍了如何使用蓝鸟地图和返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用map bluebird(Promise lib),但要返回一个对象而不是数组.

I need to use the map bluebird (Promise lib) but to return an object, instead of an array.

目前,我正在像这样使用它(但这是错误的):

Currently, I'm using it like this (but it is wrong):

return new Promise(function(resolve, reject) {
  return Promise.map(files, function(file) {
      // LOGIC

      resolve({
        // object here
      })
  }, { concurrency: 3000 })
});

原因很简单:我需要并发数:3000,并且我需要返回对象.因此,新的Promise是返回对象,而不是数组,而映射是由于并发性.

The reason is simple: I need the concurrency: 3000, and I need to return the object. So the new Promise is to return the object, and not an array, and the map is because of the concurrency.

蓝鸟还有其他方法可以帮助我实现所需的东西吗?我搜索了很多,却没有找到任何东西.

Are there any other methods of bluebird which could help me achieve what I need? I searched a lot and I didn't find anything.

推荐答案

如果您要生成以下形式的对象:

If you're trying to produce an object that is of the form:

var result = {
    file1: result1,
    file2: result2
};

其中file1file2是文件名,而result1result2是对file1file2进行一些异步操作的结果,则可以这样进行:/p>

Where file1 and file2 are the names of the files and result1 and result2 are the result of some async operation on file1 and file2, then you can do that like this:

var result = {};
return Promise.map(files, function(file) {
    return doSomeAsync(file).then(function(data) {
        // add to our result object
        result[file] = data;
    });
}, {concurrency: 3000}).then(function() {
    // make the result obj be the final resolved value of Promise.map()
    return result;
});

这将使上面的result对象成为该函数所返回的Promise.map() promise的最终解析值.

This will make the result object above be the final resolved value of the Promise.map() promise that is returned from the function this is in.

如果上面的第一个代码块不是您想要产生的对象"类型,那么请进一步详细说明您想要什么类型的输出.

If the first code block above is not the type of "object" you want to produce, then please explain further exactly what type of output you want.

此外,您可能希望避免使用承诺反模式在其中创建不必要的承诺,而不仅仅是连锁或返还已经拥有的承诺.

Also, you probably want to avoid the promise anti-pattern where you create unnecessary promises rather than just chain or return the ones you already have.

这篇关于如何使用蓝鸟地图和返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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