javascript - 等待由同步函数 Javascript 包装的嵌套函数
问题描述
提示很简单,但不幸的是,我无法找到解决方案。
我必须提交一个创建 API,然后更新 API。通常,我可以做承诺、异步/等待,甚至回调。但是,createAPI 由 formData 函数(getLength) 包装,因为它需要附加文件。因此,我无法在触发更新之前等待内部 API。
由于 getLength 不返回任何东西并且它不是一个承诺,我不确定我如何能够解决这个问题?谢谢!
const createFunc = async () => {
formData.getLength(async (err, length) => {
await platformAPI
.createAPI(formData, length)
.then((res) => {
if (res !== 201) {
console.log("something went wrong")
}
console.log("it works")
});
});
}
const apiFunc = () => {
createFunc().then(() => updateApi())
}
解决方案
你可以承诺 formData.getLength
。要么使用 Nodeutil.promisify
来获取 的承诺版本getLength
,要么自己承诺,如下所示:
// Promisify getLength:
const promiseLength = formData =>
new Promise((resolve, reject) =>
formData.getLength((err, length) => err ? reject(err) : resolve(length))
);
const createFunc = () =>
promiseLength(formData).then(length =>
platformAPI
.createAPI(formData, length)
.then(res => {
if (res !== 201) console.log("something went wrong")
else console.log("it works"); // Only print this in the else-case
return res; // Better return the value
});
);
请注意,async
当该函数中的唯一语句是await
. 在这种情况下,只需返回等待的表达式并删除async
关键字。而你的第二次使用async
甚至没有await
... 所以那是没用的。
推荐阅读
- php - Laravel 控制器显示错误尝试获取非对象的属性“地址”
- react-native - 在本机反应(Expo)中显示blob图像
- dll - 使用 Visual Studio 代码生成 C/C++ DLL
- css - 样式跨度线 i if-var 关系中的悬停效果
- c# - 使用 PsExec 和 C# 运行远程程序 - 已连接但无法正常工作
- yii2 - 如何修复 PHP 致命错误 – yii\base\ErrorException Class 'Swift_Transport_EsmtpTransport' not found
- javascript - Sinon clock.tick 不会为 setTimeout 提前时间
- javascript - 使用箭头函数设置变量
- angular - ionic 3 - 键盘推全屏
- php - 在查询中使用结果