【发布时间】:2021-05-18 09:54:44
【问题描述】:
我正在尝试调用一个函数,并且基本上强制它等待响应,然后再继续下一件事。
我有两个函数,都是异步的。
第一个看起来像这样,所有以“_”开头的参数都用作回调:
async function formatJson(input, _sendToThirdParty, _handleLogs, _setDimensions)
{
...do some work here to format the payload
if(onlineConnectionRequired)
{
_setDimensions(itemToUpdate, object);
}
else {
// Do non-online based transformations here
}
...do more work after the above
}
基本上,我正在尝试调用这个方法 setDimensions,如下所示:
async function setDimensions(itemToUpdate, object) {
try
{
if(itemToUpdate != null)
{
console.log("Loading dimensions");
await Promise.resolve(function() {
ns.get(`inventoryItem/${object['Item ID']}?expandSubResources=true`)
.then((res) => {
console.log("Inventory Item Loaded. Updating dimensions...");
itemToUpdate.consignments.push(
{
consignmentID: object.conID,
barcode: object.barcode,
itemID: '', // leaving as empty for now
width : res.data.custitem_width,
length : res.data.custitem_length,
height : res.data.custitem_height,
weight : res.data.custitem_weight,
fragile: object.fragile === 'T' ? 1 : 0,
description: object.description
}
);
console.log("Dimensions Finalised");
})
});
}
}
catch(err)
{
console.log(err);
const message = `Error attempting to set the dimensions for ${object['Item ID']}`;
console.log(message);
throw new Error(message);
}
}
我遇到的问题是:
- 第一种方法的代码在等待 Promise 解决之前继续运行,但我需要它等待,这样我才能完全构建有效负载,然后再继续执行下一个位
- 如果我尝试在第一种方法中调用
_setDimensions(...)之前包含await关键字,则会收到错误 “SyntaxError: await is only valid in async function”,但我会认为它是一个异步函数吗?
如果有人可以提供帮助,那将不胜感激!谢谢!!
【问题讨论】:
-
使用promise构造函数而不是
Promise.resolve -
ns.get看起来已经返回了一个承诺 -
第一个函数中回调的
_setDimensions参数是否正在调用第二个函数?或者它只是你的回调函数的命名偏好?其次,为什么不使用单个回调并根据回调数据继续工作? -
函数
_setDimentions是否返回一个Promise?其次,await Promise.resolve()可能会在回调完成之前立即解决。你应该改用new Promise()。 -
"我会认为它是一个异步函数?" - 是的,
formatJson是async function。请向我们展示您尝试过的确切代码,不要省略任何内容。
标签: javascript node.js asynchronous