Express 爬虫`Promise` 把异步变成同步问题?

图片描述

clipboard.png

为什么 console.log("Promise",helper.httpClient()); 的结果是 undefined。看这个打印的信息,分明这里router.get()Promise 并没有把异步变成同步,没有等 helper.httpClient() 结果的返回就已经往下执行了?

Node.js的版本是 v8.9.0 ,系统是centos7.
Promise undefined
arr.length undefined
GET /main 304 283.076 ms - -
GET /stylesheets/style.css 304 3.099 ms - -
GET /javascripts/echarts.min.js 304 2.888 ms - -
arr.length123 xxxx
arr.length123 xxxx
xxxx 这个是爬回来的结果。
阅读 3.6k
2 个回答

你的httpClient函数应该返回一个promise对象,调用也应该是 httpClient().then ,或者用 async/await 的写法:

const httpClient = function () {
    const options = {
        // ...
    };
    return new Promise((resolve, reject) => {
        http.get(options, (res) => {
            // ...
            // 你的 error 哪去了?
            res.on('end', () => {
                resolve(tr)
            })
        })
    })
}


//调用-- async/await,基于promise
router.get('/', async (req, resp, next) => {  
    let promise = new Promise(async (resolve, reject)=>{
        const result = await httpClient();
    })
})

httpClient函数还是被调用有没有指定return,就是默认返回undefinded
而你需要做的就是:
传入一个回调函数给httpClient



function httpClient(callback){

    new Promise(function(resovle,reject){
        //模拟异步执行
        setTimeout(function(){
            resovle("DONE~~~~~");
            //reject(new Error("failed"));
        },1000);
    }).then(function(resultData){
        console.log("++++")
        callback&&callback.apply(null,[null,resultData]);
    }).catch(function(error){
        callback&&callback.apply(null,[error]);
    });
}


function runHttpClient(){
    new Promise(function(resovle,reject){
        httpClient(function(error,data){
            if(error){
                reject(error);
                return;
            }
            resovle(data);
        });
    }).then(function(result){
        console.log(">>>"+result);
    }).catch(function(error){
        console.err(error);
    });
}

runHttpClient();

或者让httpClient返回一个promise

function httpClient_promise(){

    return new Promise(function(resovle,reject){
        //模拟异步执行
        setTimeout(function(){
            resovle("DONE~~~~~");
            //reject(new Error("failed"));
        },1000);
    });
}

function runHttpClient2(){
    httpClient_promise().then(function(result){
        console.log(">>>"+result);
    }).catch(function(error){
        console.err(error);
    });
}

runHttpClient2();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题