Await是一个由同步函数Javascript包装的嵌套函数



提示很简单,但不幸的是,我没能找到解决方案。

我必须提交一个创建API,然后更新API。通常,我可以进行promise、async/await,甚至回调。但是,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。要么使用Node的util.promisify来获得getLength的promised版本,要么自己promised,如下所示:

// 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
});
);

注意,当函数中唯一的语句是await时,async没有多大用处。在这种情况下,只需返回等待的表达式并删除async关键字。你第二次使用async甚至没有await。。。所以那是没有用的。

您可以使用Promise构造函数将.getLength转换为基于Promise-based的API,然后您可以将其转换为await:

const createFunc = async () => {
const length = await new Promise ((rs, rj) => {
formData.getLength((err, length) => {
if(err)
rj(err);
else
rs(length);
});
})
//This part with the `then` was OK, but since you're already using `async/await`, there's no reason why you shouldn't use it here too
const res = await platformAPI.createAPI(formData, length)
if (res !== 201) {
console.log("something went wrong")
}
console.log("it works")
}

const apiFunc = () => {
createFunc().then(() => updateApi())
}

我认为您分离实现是因为formData.getLength函数不是promise函数。您不应该同时使用回调和等待。我认为这不是一个好的做法。如果我们可以使用wait-use,那么格式会更干净。

const getLengthFunc = new Promise(function(resolve, reject) {
formData.getLength((err, length) => {
if(err)
reject('error');

resolve(length)
}
});
const createFunc = async () => {
try{
const length = await getLengthFunc();
const res = await platformAPI.createAPI(formData, length);
if (res !== 201)
console.log("something went wrong")

console.log("it works")
}catch(e){
console.log(e)
}
}

const apiFunc = () => {
createFunc().then(() => updateApi())
}

最新更新