javascript - lodash mapValues 异步

标签 javascript node.js lodash

在 _.mapValues 中,我想获得一些具有一定延迟的修改值(例如来自数据库),但我遇到了问题:当我在同步模式下修改值时,一切都很好,当我尝试使用 promise 或回调它的工作时不正确(在第一种情况下我得到 Promise 对象,在第二种情况下:未定义的值)。 这里有一些简化的例子,我如何重写 mapValues 中的代码来解决这个问题?

'use strict';
const _ = require('lodash');
const Promise = require('bluebird');

let obj = {
  one: 1,
  two: 2,
};

let increment = (value) => {
  return value + 1;
};

let incrementProm = (value) => {
  return Promise.resolve(value + 1);
};

let incrementCb = (value, cb) => {
  let res = value + 1;
  let err = null;
  setTimeout(cb.bind(undefined, err, res), 100);
};

let t1 = _.mapValues(obj, (value) => {
  return increment(value);
});

let t2 = _.mapValues(obj, (value) => {
  return incrementProm(value);
});

let t3 = _.mapValues(obj, (value) => {
  let temp;
  incrementCb(value, (err, res) => {
    temp = res;
  });
  return temp;
});

console.log('Sync res:');
console.log(t1);
console.log('Promise res:');
console.log(t2);
console.log('Callback res:');
console.log(t3);

最佳答案

您可以使用 bluebird 的 props()函数来解析所有带有 promise 的属性。

Promise.props(_.mapValues(obj, incrementProm))
.then(result => console.log(result));

var obj = {
  one: 1,
  two: 2
};

var incrementProm = value => Promise.resolve(value + 1);

Promise.props(_.mapValues(obj, incrementProm))
.then(result => console.log(result));
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.4.1/bluebird.js"></script>

关于javascript - lodash mapValues 异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38125401/

相关文章:

javascript - 2048 : Strange behaviour of reduceRight in map with lodash/fp

javascript - 使用 JavaScript 从 Firebase 下载为 JSON

javascript - 来自 PEM 的 SubtleCrypto importKey

javascript - 通过 Firebase 功能发送时 FCM 出现高延迟

javascript - 使用 lodash 或 JS 按值对对象数组进行排序

javascript - 我可以使用另一个 _.get 作为 lodash _.get 的默认值吗?

javascript - Canvas 未合并并导致仅显示背景图像

javascript - 使用 jQuery 调整加减按钮

node.js - 如何在 Express 中捕获(或记录)Response 对象的数据?

AngularJS/NodeJS 应用程序与 Paypal In-Context Checkout 集成