为什么在异步代码上console.log()可以工作,而array.push()不能工作?

时间:2019-01-04 09:08:05

标签: javascript node.js asynchronous axios

我有这段代码,它试图跟踪URL的所有重定向。 console.log()对于单个响应正确输出所有内容,但是当我尝试输出response.push()的结果时,它只输出相同输出的X倍。

我正在使用Node v8.12和Axios 0.18

const axios = require('axios')

const instance = axios.create({
    maxRedirects: 0
})

var HttpResponse = {
    status: '',
    statusText: '',
    location: '',
    headers: {}
}

let url = 'url with redirects here'

const doCall = async function(url){

    return instance.get(url)
    .then((response) => {

        let newresponse = HttpResponse
        newresponse.status = response.status
        newresponse.statusText = response.statusText
        newresponse.headers = response.headers
        return {
            final: true, 
            response: newresponse
        }
    })
    .catch((err) => {
        if( err.response ){

            let newresponse = HttpResponse
            newresponse.status = err.response.status
            newresponse.statusText = err.response.statusText
            newresponse.headers = err.response.headers

            return {
                final: false, 
                response: newresponse
            }

        }else{

            let newresponse = HttpResponse
            return {
                final: true,
                response: newresponse
            }
        }
    })
}

const start = async function(){

    let responses = []
    let result = await doCall(url)
    console.log(result)
    responses.push(result)

    while( result.final != true ){
        result = await doCall(result.response.headers.location)
        console.log(result)
        responses.push(result)
    }

    console.log(responses)
}

start()

每个console.log的输出,但最后一个使用带有301重定向的URL的输出:

{final: false, ...}
{final: true, ...}

console.log的输出(响应):

[{final: true, ...}
{final: true, ...}]

为什么response.push()不能按预期工作?

1 个答案:

答案 0 :(得分:0)

我刚刚为您的代码创建了简单的POC,无需特殊要求即可运行,它就像一个魅力。

let i=0;

const doCall = async function(url){

    return Promise.resolve()
    .then((response) => {
        if (i > 4) {
            return {final: true};
        }
        return { final: false};
    })
}

const start = async function(){

    let responses = []
    let result = await doCall()
    console.log(result)
    responses.push(result)

    while( result.final != true ){
        result = await doCall()
        console.log(result)
        responses.push(result)
        i++;
    }

    console.log(responses)
}

start();

可能还有其他问题,您是否可以提供更多代码?您可以复制代码的完整输出吗? (即使用node server.js > output.txt运行它),然后提供完整的输出?