首页 > 解决方案 > 如何返回递归获取的结果?

问题描述

我有第一个异步函数

fetch("https://api.priceapi.com/v2/jobs", {
            body: body,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: "POST"
                }).then((response) => {
                            return response.json();
                        }).then((data) => {

                            return fetchRepeat(data.job_id)
                        })

以及第二个递归异步函数。

function fetchRepeat(id){

    fetch("https://api.priceapi.com/v2/jobs/"+ id +"/download.json?token=" + priceapisecret.secret)
    .then((response) => {
        return response.json()
    }).then((data) =>{
        if(data.status == "finished"){

            var bookdata = {
                title: data.results[0].content.name,
                price: data.results[0].content.price
            }

            return bookdata;

        }
        else{
            fetchRepeat(id)
        }
    })
}

我希望能够在第一个异步函数中访问 bookdata。我怎么做?

标签: asynchronousrecursionfetch

解决方案


为了谈论回报fetchRepeat,您需要回报承诺。结果并没有如此返回undefined。最后一个then也没有返回递归的值,因此也解析为undefined.

这是一个工作版本:

function fetchRepeat(id) {
    // return the promise
    return fetch(`https://api.priceapi.com/v2/jobs/${id}/download.json?token=${priceapisecret.secret}`)
        .then(response => response.json())
        .then(({ status, results: [{ content: { name: title, price } }] = [{ content: {} }] }) =>
            (status === 'finished' ? { title, price } : fetchRepeat(id))); // return result of recursion
}

现在我让 ESLint 处理格式,因为我使用 airbnb,它更喜欢解构。最后一个错误then很明显,因为 ELSint 抱怨返回一致。我强烈建议您使用 linter 和 IDE 来强制编码风格,以减少代码中的错误并使其他人更容易阅读。


推荐阅读