我目前正在节点上的项目中工作,首先应该发送POST请求,然后再发送GET请求,该请求取决于POST请求的响应。有人对此有什么建议吗?我正在使用axios和express。异步/同步的事情开始引起我的注意。
我的代码
const express = require("express");
const PORT = process.env.PORT || 3000;
var axios = require("axios");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("Public"));
var url1 = "https://api.playground.klarna.com/checkout/v3/orders/";
var url2 = "https://api.playground.klarna.com/checkout/v3/orders/";
//POST
var axios = require("axios");
var data = JSON.stringify({
purchase_country: "SE",
purchase_currency: "SEK",
locale: "sv-SE",
order_amount: 50000,
order_tax_amount: 4545,
order_lines: [
{
type: "physical",
reference: "19-402-USA",
name: "Red T-Shirt",
quantity: 5,
quantity_unit: "pcs",
unit_price: 10000,
tax_rate: 1000,
total_amount: 50000,
total_discount_amount: 0,
total_tax_amount: 4545,
},
],
merchant_urls: {
checkout:
"https://atelierdecosmetique.herokuapp.com/checkout?sid={checkout.order.id}",
confirmation:
"https://atelierdecosmetique.herokuapp.com/confirmation?sid={checkout.order.id}",
push: "https://www.example.com/api/push",
},
});
var config = {
method: "post",
url: url1,
headers: {
"Content-Type": "application/json",
Authorization:
"",
},
data: data,
};
//GET
var axios = require("axios");
var data1 = "";
var config1 = {
method: "get",
url:
url2,
headers: {
"Content-Type": "application/json",
Authorization:
"",
},
data: data1,
};
axios(config)
.then(response => {
return axios(config1)
}).then(response => {
})
.catch(err => console.log(err))
app.listen(PORT);
答案 0 :(得分:1)
由于您未显示任何代码,因此我们只能从概念上回答。由于使用async/await
最容易对诺言进行排序,因此我选择在此处向您展示该模型:
async function someFunction() {
const postResult = await axios.post(someUrl, someData);
const getResult = await axios.get(someUrl2, {params: {can use postResult in here}});
// further processing
return something;
}
// call it like this
somefunction().then(finalResult => {
console.log(finalResult);
}).catch(err => {
console.log(err);
});
如果您显示实际代码,我们可以显示更多细节。