如何从.then块返回响应?

时间:2019-05-21 15:26:04

标签: node.js

我有一个使用Axios库进行HTTP调用的方法,
HTTP工作正常,但是我无法从.then块返回数据,

以下是我的方法-

module.exports.postAPI = async (url, headers, data) => {

    console.log("URL => ", url);
    console.log("Payload => ", headers);
    console.log("Data => ", data);

    await axios({ method: 'POST', url: url, headers: headers, data: data })
    .then((response) => {
        console.log("POST API Call Successful \n");  
        console.log("POST Response => \n", response.data); 
        return response.data;
    })
    .catch((error) => {
        console.log("POST API Call Unsuccessful \n", error,"\n");
        return error;
    });
}

调用postAPI-

let test = async () => {

    let url = 'someURL';

    let headers = {
        "Content-Type": "application/json"
    };

    let data = {
            "someKey": "someValue"
    };

    let response = await commonUtil.postAPI(url, headers, data);
        console.log("UTIL Response => \n", response);
}

POST API Call Successful and POST Response => and response.data正在打印,
但是数据没有返回给调用函数。

2 个答案:

答案 0 :(得分:1)

使用Async / await或Promise

异步/等待

    module.exports.postAPI = async (url, headers, data) => {

    console.log("URL => ", url);
    console.log("Payload => ", headers);
    console.log("Data => ", data);
    try{

         let response=await axios.post(url,data, {headers: headers} )
         console.log("POST API Call Successful \n");  
         console.log("POST Response => \n", response.data); 
         return response.data;
    }
    catch(err){
         console.log("POST API Call Unsuccessful \n", err,"\n");
         return err
    }
}

承诺

module.exports.postAPI = (url, headers, data) => {

    console.log("URL => ", url);
    console.log("Payload => ", headers);
    console.log("Data => ", data);

    axios.post(url,data, {headers: headers} )
    .then((response) => {
        console.log("POST API Call Successful \n");  
        console.log("POST Response => \n", response.data); 
        return response.data;
    })
    .catch((error) => {
         console.log("POST API Call Unsuccessful \n", error,"\n");
         return error;
    });
}

答案 1 :(得分:1)

module.exports.postAPI = async (url, headers, data) => {
  try {
     const { data } = await axios({ method: 'POST', url: url, headers: headers, data: data });
     return data;
} catch(error){
    return error;
});

}

相关问题