gpt4 book ai didi

javascript - NodeJs waterfall 回调功能不起作用

转载 作者:行者123 更新时间:2023-12-03 05:42:48 26 4
gpt4 key购买 nike

我正在使用npm异步 waterfall 方法来编写功能。在那里我发现了一个奇怪的情况(可能是我的意识低)。我的功能如下。我在第一个函数中创建一个事件数组,并通过回调参数将其传递给第二个函数。然后我在第二个函数中捕获该数组并循环它。我想操作数组的几个值。之后我将其发送到最终函数。

最终函数中的console.log语句仅输出第一个函数中数组的初始状态,而不输出我在第二个函数中所做的操作。任何想法都会受到高度赞赏。

var _async = require('async');
var criteria = {};

_async.waterfall([
function getSortedCalenderItems(callback){
var events = []; // set of events are included inthis array
callback(null, events)
},

function getUsers(events, callback) {
for (var i = 0; i < events.length; i++) {
var event = events[i];
var user = event.shared_user;

// manipulate user
var newUser = {
'id' : '<id>',
'name' : 'New name'
};

event.shared_user = newUser;
events[i-1] = event;

if(i === (events.length)) {
callback(null, events)
}
}

}
],function(err, events){
console.log(events); // this shows the initial state of the array. Not the manipulated events array.
return;
});

最佳答案

例如;

var _async = require('async');
var criteria = {};

_async.waterfall([
function (callback) {
var events = [// set of events are included inthis array
{
name: "event1",
shared_user : "halil"
}, {
name: "event1",
shared_user : "halil"
}
];
callback(null, events);
},
function (events, callback) {
console.log(events)
for (var i = 0; i < events.length; i++) {
var event = events[i];
var user = event.shared_user;

// manipulate user
user = {
'id': '<id>',
'name': 'New name'
};

if (i === (events.length - 1)) {
callback({}, events)
}
}
}
], function (err, events) {
console.log(err, events);
});

关于javascript - NodeJs waterfall 回调功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40463765/

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