在 _.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/