gpt4 book ai didi

arrays - Node.js promise : Push to array asynchronously & save

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:38 26 4
gpt4 key购买 nike

我目前正在尝试从通过请求收到的项目列表中推送到一个数组(Mongo 模型中的属性)。从这些项目中,我遍历它们以查看数据库中当前有哪一个,如果不是这样,那么我创建一个新项目并尝试保存它。我正在使用 promises 来完成此任务,但我无法弄清楚为什么在所有 promise 都已履行后数组为空。

var q     = require('q');

var items_to_get = ['1', '2', '3']; // example array

var trans = new Transaction({
items : []
});

var promises = [];

for (var i = 0; i < items_to_get.length; i++) {

var ith = i; //save current i, kinda hacky
var deferred = q.defer(); //init promise

//find an existing item
Item.findOne({simcode: items_to_get[ith]}, function(err, item) {
trans.items.push(item); // push item to transaction
deferred.resolve(item); // resolve the promise
});
promises.push(deferred); // add promise to array, can be rejected or fulfilled
};

q.allSettled(promises).then(function(result) {
console.log(trans.items); //is empty
trans.save();
}

编辑 已解决:下面的代码,基于 http://jsbin.com/bufecilame/1/edit?html,js,output .. 致谢@macqm

var items_to_get = ['1', '2', '3'];
var promises = []; //I made this global

items_to_get.forEach(item) {
upsertItem(item);
}

q.allSettled(promises).then(function(result) {
//loop through array of promises, add items
result.forEach(function(res) {
if (res.state === "fulfilled") {
trans.items.push(res.value);
}
});
trans.save();
promises = []; //empty array, since it's global.
}

//moved main code inside here
function upsertItem(item) {
var deferred = q.defer(); //init promise
//find an existing item
Item.findOne({simcode: item}, function(err, item) {
deferred.resolve(item); // resolve the promise
// don't forget to handle error cases
// use deffered.reject(item) for those
});
promises.push(deferred); // add promise to array
}

最佳答案

这就是我在没有任何第 3 方库的情况下的做法。

由于我只是需要推迟,而且我正在使用 ES2017,所以我认为最好不要使用不必要的依赖项使事情过于复杂。

'use strict';

/**
* @param {function(*)} callee
* @param {Array} args
* @returns {Promise.<*>}
*/
const defer = (callee, args) => {
return new Promise(resolve => {
resolve(callee(...args));
});
};

/**
* @param {Number} one
* @param {Number} two
* @param {Number} timeout
* @returns {Promise.<Number>}
*/
const asyncFunction = (one, two, timeout) => {
return new Promise(resolve => {
setTimeout(resolve, timeout, one + two);
});
};

let promises = [];
promises.push(defer(asyncFunction, [3, 7, 0])); // returns immediately
promises.push(defer(asyncFunction, [10, 20, 100])); // returns after 100ms
promises.push(defer(asyncFunction, [55, 45, 50])); // returns after 50ms

Promise.all(promises).then(results => {
console.log(results);
});

运行上面的代码,你会得到[ 10, 30, 100 ]

关于arrays - Node.js promise : Push to array asynchronously & save,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29185579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com