函数 returns 未定义而不是请求的结果

Function returns undefined instead of result of the request

我在 javascript 中遇到一些异步问题。有一个函数(下一个)重复发送 REST API 请求到服务器。这些函数将调用自身,直到找到根 ID。你可以在现场找到console.log('the root ID is reached!')。之后,我需要最后一个请求 ID 作为函数 (next) 的返回结果,而是 returns "undefined".((

function next(initId) {
       return requestHttp('GET','https://www.wrike.com/api/v4/folders/' + initId)
        .then(function(response: string) {
            let folderObj =  JSON.parse(response);
            initId = folderObj.data[0].parentIds;
            if (folderObj.data[0].parentIds === WebHook.rootId) {
               console.log('the root ID is reached!');
               return folderObj.data[0].id;
            } else {
                next(initId); 
            }   
        }, function(error) {
            return error;
        });      
}

next(obj.data[0].parentIds).then(function(response) {
    console.log(response);
}).catch(function(err) {
    console.log(err);
});

尝试 return Promise.resolve(initId) 而不是 next(initId)

根据 Wrike.com api,您不必执行此操作来查找根文件夹 ID。 https://developers.wrike.com/documentation/api/methods/get-folder

[GET] /folders/{folderId} returns a parentIds 属性 这是父文件夹 ID 的数组。

我没有帐户,但我很确定此数组中的第一个或最后一个(取决于顺序)是您不想找到的 ROOT 文件夹 ID。

编辑

我不太确定您要做什么,但与此同时,您的代码中有几个基本错误需要修复:

首先,这是 return 链式承诺

的正确方法
function next(initId) {
    let promise = new Promise(function(resolve, reject) {
    requestHttp('GET','https://www.wrike.com/api/v4/folders/' + initId)
        .then(function(response) {
            if(/*condition to resolve promise*/) {
                resolve(/*with something*/);
            }
            else {
                reject(/*with an error*/);
                // or return another Promise
            }
        })
        .catch(error => reject(error));
    });
    return promise;            
}

然后,next 方法接受一个名为 initId 的参数,因此其他开发人员(例如我们)不会认为它是一个 id 数组。

我的意思是,这很令人困惑。它之所以有效,是因为 parentIds 属性 是一个数组,而这个数组的 .toString() returns id1,id2,...

Wrike api 支持,但您应该使用 ids.join(',')

function next(initId, taskId) {
    let promise = new Promise(function(resolve, reject) {
     (async function nextRequest (){   
     await requestHttp('GET','https://www.wrike.com/api/v4/folders/' + initId)
            .then(function(response: any) {
                let folderObj = JSON.parse(response);
                initId = folderObj.data[0].parentIds[0];
                if (initId == WebHook.rootId) {
                    resolve('resolve');
                }
                else {
                    nextRequest();
                }
            })
            .catch(error => reject(error));
        }());
    });
    return promise;            
}

next(obj.data[0].parentIds, true).then(function(response) {
    console.log(response);
}).catch(function(err) {
    console.log(err);
}); 

问题的答案