gpt4 book ai didi

javascript 在嵌套函数中将项目添加到全局数组,更改不会反射(reflect)在使用 gmail api 的外部

转载 作者:行者123 更新时间:2023-12-03 07:42:57 25 4
gpt4 key购买 nike

所以我有这个代码

  function addEmail(e){
emails.push(e);
}
var emails = new Array;

function getMessage( messages, callback ) {

var get = function(len){


//console.log(messages[len].id);
var request = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': messages[len].id
});
request.execute(function(response){
var e = parseMessages(response)
//console.log(JSON.stringify(e));
addEmail(e);

});
len++;

if(len<messages.length){
console.log(emails.length);
get(len);
}
else{
console.log(emails.length);
process(emails);
}

}
get(0);


};

当我尝试在方法 getMessage 之外访问电子邮件数组时,它是空的。这行代码“console.log(emails.length);”总是打印 0,
但是,当我将这行代码放入 get 方法中时,它显示值正在添加到数组中

最佳答案

when i am trying to access the emails array outside the method getMessage it is empty. this line of code "console.log(emails.length);" always prints 0

时机!

我很确定,您想构建这个:

function getMessage( messages, callback ) {
var emails = [];
get(0);

function get(index){
if(index === messages.length){
return callback(emails);
}

//console.log(messages[index].id);
var request = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': messages[index].id
});

request.execute(function(response){
var e = parseMessages(response)
//console.log(JSON.stringify(e));
emails.push(e);
get(index+1);
});
}
}


getMessage( someMessages, function(emails){
console.log(emails);
})

或并行:

function getMessage( messages, callback ) {
function done(){
if(--pending) return; //still work left
callback(emails);
}

var pending = 1,
emails = Array(messages.length);

messages.forEach(function(msg, i){
++pending;

var request = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': msg.id
});

request.execute(function(response){
emails[i] = parseMessages(response);
done();
});
});

done();
}
  • 未经测试

关于javascript 在嵌套函数中将项目添加到全局数组,更改不会反射(reflect)在使用 gmail api 的外部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329197/

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