我正在使用 NodeJS。我的一个函数(我们称之为 funcOne)接收一些输入,我将其传递给另一个函数(我们称之为 funcTwo),该函数会产生一些输出。
在将输入传递给 funcTwo 之前,我需要对传递输入的端点进行 Ajax 调用,然后必须将 AJAX 调用产生的输出传递给 funcTwo。仅当 AJAX 调用成功时才应调用 funcTwo。
如何在 NodeJS 中实现这一点。我想知道在这种情况下是否可以使用Q Library
function funcOne(input) {
var request = require('request');
request.post(someUrl, {json: true, body: input}, function(err, res, body) {
if (!err && res.statusCode === 200) {
funcTwo(body, function(err, output) {
console.log(err, output);
});
}
});
}
function funcTwo(input, callback) {
// process input
callback(null, input);
}
编辑:由于请求现已被弃用,您可以在您还可以使用最新版本的nodejs(18+)附带的内置fetch API。请参阅下面的示例。
async function funcOne(input) {
try {
const response = await fetch(someUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(input),
});
if (response.ok) {
const body = await response.json();
funcTwo(body, (err, output) => {
console.log(err, output);
});
}
} catch (err) {
// Handle errors here
console.error(err);
}
}
function funcTwo(input, callback) {
// process input
callback(null, input);
}
npm install [email protected]
const axios = require('axios');
axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
.then(response => {
console.log(response.data.url);
console.log(response.data.explanation);
})
.catch(error => {
console.log(error);
});
使用标准http库发出请求将需要更多的精力来解析/获取数据。对于习惯于纯粹使用 Java/JavaScript 发出 AJAX 请求的人来说,我发现 axios 很容易上手。
https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html