首页 > 解决方案 > 等待由同步函数 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())
}

标签: javascriptasync-awaitpromiseform-data

解决方案


你可以承诺 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... 所以那是没用的。


推荐阅读