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。