I want to create a function that returns the value obtained in the request in Node.js as a return value.

Asked 2 years ago, Updated 2 years ago, 88 views

I would like to do something like taping the API based on the results obtained from the API.
When I use the request module, is there only a way to write continuously in the function?(Arrow Location)

 request.get({
    uri —URL,
    headers: {'Content-type': 'application/json'},
    qs: {
        // follow the GET URL
        // ?hoge=huga part
    },
    json —true
}, function(err,req,data){
    console.log(data);←
});

Code Quotation: https://qiita.com/yuta0801/items/ff7f314f45c4f8dc8a48
I want to hit the API using the results of using the API multiple times, so I would like to take out the data part that is the result.
I tried result=request.get, but I could only get information about the request.
We look forward to your kind cooperation.

node.js api

2022-09-30 14:18

1 Answers

README introduces how to use promise instead of callback. There are two ways to use wrapper libraries and Node.js promise.

For example, if you use request-promise-native, you can write:

const request=require("request-promise-native");

(async function(){
    try{
        const data = wait request.get("https://www.example.com");
        console.log(data);
    } catch(err){
        // error handling
    }
})();


2022-09-30 14:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.