使用另一个调用请求的功能的NodeJS路由器不等待答案

时间:2019-04-09 17:47:04

标签: javascript node.js async-await request

我有一些路线:

router.get('/test', async function (req, res, next) {
    let someValue = await someFunction();
    console.log(someValue);
}

还有一个向其他服务发出GET请求的函数:

async function someFunction() {
let options = {
    url: `someURL`,
    method: 'GET',
};
request(options, async function (error, response, body) {
    if (error) {
        throw error;
    } else {
        return body['someSpecificValue'];
    }
});

}

,但是,在我的路由器中,someValue似乎始终打印为undefined

我在做什么错?我该如何正确地等待someURL的回答?

2 个答案:

答案 0 :(得分:2)

您可以使用异步的node-fetch模块,而不是请求

npm i node-fetch

这是一个例子

const fetch = require("node-fetch");
const url = "https://jsonplaceholder.typicode.com/posts/1";
const getData = async url => {
  try {
    const response = await fetch(url);
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  }
};
getData(url);

答案 1 :(得分:1)

因为someFunction不会像下面那样返回承诺更新或使用request-promise

var rp = require('request-promise');

function someFunction() {
    let options = {
        url: `someURL`,
        method: 'GET',
    };
    return rp(options);
}

OR

                <ReferenceInput label="Tipus" source="type" reference="categories" validate={ required() } >
                    <AutocompleteInput optionText="name" />
                </ReferenceInput>
                <FormDataConsumer>
                    {({formData, ...rest}) => {
                        console.log(formData)
                        if ( formData.type !== undefined ) {
                            var t = formData.type;
                            var myType = t.toString();
                            var myOptionText = `${myType}.name`
                        }
                        return (
                                    <ReferenceArrayInput label="Categories dynamic" source={myType} reference="categories" {...rest}>
                                        <SelectArrayInput optionText="name" />
                                    </ReferenceArrayInput>
                        )
                       }}
                </FormDataConsumer>