0
function getData() {
return new Promise(function (resolve, reject) {
    request({
    url: 'https://jsonplaceholder.typicode.com/posts',
    method: "GET",
    },
   function (err, res, body) {
    if(!err)
    resolve(res);
    else
    reject(err);
});
})  
}
   getData().then((val) => {
        module.exports = val;
   });

在这里,我使用 REST API 通过 request npm 模块获取一些数据。由于请求不返回承诺,所以我将其包装在承诺中并解决响应。后来,我将 .then() 放入返回 promise 的函数中,然后在 .then() 中放入 module.exports = val。但是,我不想将 module.exports 放入 .then() 中。

有没有其他方法可以将数据异步获取到 module.exports。

4

1 回答 1

2

在这种情况下,应该返回承诺。.thenorawait应该由导入和调用此模块/函数的代码实现。

于 2020-04-15T22:03:16.813 回答