我使用交付定制框架制作了一个shopify应用程序。它在run.js中有一个函数
//...Above code
export async function run(input) {
const configuration = JSON.parse(
input?.deliveryCustomization?.metafield?.value ?? "{}"
);
const axios = require('axios');
var x = 10;
try {
const response = await axios.post(functionUrl, data, {
headers: {
'Content-Type': 'application/json'
//,'x-functions-key': functionKey
}
});
x = 5;
} catch (error) {
x = 2;
}
//More code...
shopify 似乎不允许异步调用,我如何在不使用 async/await 的情况下调用 azure 函数。
我尝试使用与 axios 不同的库(fetch),但这不起作用。 我尝试过使用“then, catch”块来使用基于承诺的系统,但这也不起作用。
要在不使用
async/await
的情况下从 Shopify 应用程序函数调用 Azure 函数,您可以使用传统的基于承诺的方法以及 .then
和 .catch
。
这样,您就可以避免使用
async/await
并使用 Promise 处理 HTTP 调用的异步性质。
以下是使用
axios
实现此操作的方法:
const axios = require('axios');
export function run(input) {
const configuration = JSON.parse(
input?.deliveryCustomization?.metafield?.value ?? "{}"
);
const functionUrl = 'YOUR_AZURE_FUNCTION_URL';
const data = {
// Your data here
};
var x = 10;
axios.post(functionUrl, data, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
x = 5;
})
.catch(error => {
x = 2;
});
// More code...
}
下面的示例代码使用
axios
调用给定的 Azure 函数代码。
const { app } = require('@azure/functions');
const axios = require('axios');
app.http('httpTrigger1', {
methods: ['GET', 'POST'],
authLevel: 'anonymous',
handler: async (request, context) => {
context.log(`Http function processed request for url "${request.url}"`);
const name = request.query.get('name') || 'world';
const functionUrl = 'YOUR_URL';
const data = {
// Your data here
};
var x = 10;
axios.post(functionUrl, data, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
x = 5;
context.log('Response from Azure Function:', response.data);
})
.catch(error => {
x = 2;
context.log('Error calling Azure Function:', error.message);
});
return { body: `Hello, ${name}! The value of x is ${x}.` };
}
});