gpt4 book ai didi

javascript - 如何使用 Promises 在 Node 中编写同步函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:41 24 4
gpt4 key购买 nike

1.如何在 Node 中同步编写 Promise,以便获得我想要的输出。我是新手,非常感谢任何帮助/建议。

// This is my core function

var compareData = function(userIdArray) {
return new Promise(function(resolve, reject) {
var missingArray = new Array();
userIdArray.forEach(function(id) {
var options = {
method: 'POST',
url: 'http://localhost:6006/test1',
headers:{
'content-type': 'application/json' },
body: { email: id },
json: true
};

request(options, function (error, response, body) {
missingArray.push(body);
});
});
resolve(missingArray);
});
}


//I'm calling my function here

compareData(userIdArray)
.then(function(missingArray){
console.log("The Body is: "+ missingArray);
});

/* I expect the console.log to print the missingArray with data from my POST call,
but it prints an empty array. Can someone please tell me how to do this synchronously.
I'm pretty new to Node and finding it difficult to understand.*/

最佳答案

如果您不想按照@Thomas 的回答使用外部库,您可以直接使用 native Promises - 而且它并不会太冗长

var compareData = function compareData(userIdArray) {
return Promise.all(userIdArray.map(function (id) {
return new Promise(function (resolve, reject) {
var options = {
method: 'POST',
url: 'http://localhost:6006/test1',
headers: {
'content-type': 'application/json'
},
body: {
email: id
},
json: true
};
return request(options, function (error, response, body) {
error ? reject(error) : resolve(body);
});
});
}));
};

compareData(userIdArray)
.then(function (missingArray) {
console.log("The Body is: " + missingArray);
});

或者,因为这是 Node ,它可以处理更现代的代码:

var compareData = userIdArray => 
Promise.all(userIdArray.map(id =>
new Promise((resolve, reject) =>
request({
method: 'POST',
url: 'http://localhost:6006/test1',
headers: {
'content-type': 'application/json'
},
body: {
email: id
},
json: true
}, (error, response, body) => error ? reject(error) : resolve(body))
)
));

compareData(userIdArray)
.then(missingArray =>
console.log("The Body is: "+ missingArray)
);

关于javascript - 如何使用 Promises 在 Node 中编写同步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937580/

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