简体   繁体   English

如何将 promise object 中返回的 JSON object 分配到全局变量中?

[英]How to assign a JSON object returned inside a promise object into a global variable?

var mongoose = require('mongoose');
var Schema = mongoose.Schema;


const NewsAPI = require('newsapi');
const { response } = require('express');
const newsapi = new NewsAPI();

var current_date = new Date(Date.now());
var old_date = new Date(Date.now() - 864e5 - 864e5);

var current_date2 = JSON.stringify(current_date);
var old_date2 = JSON.stringify(old_date);

var today = current_date2.slice(1,11);
var day_b4_yesterday = old_date2.slice(1,11);

var feed;
newsapi.v2.everything({
    q: 'food and beverage',
    sources: '',
    domains: '',
    from: day_b4_yesterday,
    to: today,
    language: 'en',
    sortBy: 'relevancy',
    page: 2
}).then(response => {
    console.log(response);
    feed = response;

    

});


var NewsSchema = new Schema(feed);
module.exports = mongoose.model('News', NewsSchema);

I need to assign the response which is a JSON object created by the newsapi to a global variable to use it in the new Schema.我需要将由 newsapi 创建的 JSON object 的响应分配给全局变量,以便在新架构中使用它。 How do I do that?我怎么做? As of now I'm not able to access it globally.截至目前,我无法在全球范围内访问它。

I have changed my code as follows and now it I'm able to access it but now I'm getting a Schema configuration error.我已按如下方式更改了我的代码,现在我可以访问它,但现在我收到了架构配置错误。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;


const NewsAPI = require('newsapi');
const { response } = require('express');
const newsapi = new NewsAPI('87ca7d4d4f92458a8d8e1a5dcee3f590');

var current_date = new Date(Date.now());
var old_date = new Date(Date.now() - 864e5 - 864e5);

var current_date2 = JSON.stringify(current_date);
var old_date2 = JSON.stringify(old_date);

var today = current_date2.slice(1,11);
var day_b4_yesterday = old_date2.slice(1,11);


NewsLibrary = function(correct){
    var promise = new Promise(function(resolve, reject){
        if (correct){
            newsapi.v2.everything({
                q: 'food and beverage',
                sources: '',
                domains: '',
                from: day_b4_yesterday,
                to: today,
                language: 'en',
                sortBy: 'relevancy',
                page: 2
            }).then(response => {
                resolve(response);
            })
        }else{
            reject(new Error("Error loading news"))
        }
        

    });

    return promise;
}

NewsLibrary(true).then(function(response){
    console.log(response);
    var NewsSchema = new Schema(response);
    module.exports = mongoose.model('News', NewsSchema);
}).catch(function(err){
    console.log(err)
});

You have taken a global variable feed .您采用了全局变量feed But you are storing the response in window.feed .但是您将响应存储在window.feed中。 So you should store it in feed variable in the then block, That is the first thing.所以你应该把它存储在then块的feed变量中,这是第一件事。

You can assign it by using global or GLOBAL, nodejs supports both:您可以使用 global 或 GLOBAL 来分配它,nodejs 支持这两者:

global.feed = response; global.feed = 响应;

or或者

GLOBAL.feed = response; GLOBAL.feed = 响应;

I think the main problem is because the method is asynchronous.我认为主要问题是因为该方法是异步的。

var NewsSchema = new Schema(feed);

This code should only work after the request is complete.此代码应仅在请求完成后才有效。 But I think it would run before the request is complete because it is given outside the promise (the then statement).但我认为它会在请求完成之前运行,因为它是在 promise ( then语句)之外给出的。

Ideally you should return a promise from this method or a function which will return the correct value and handle the promise in the module which imports this.理想情况下,您应该从此方法返回 promise 或 function ,它将返回正确的值并在导入它的模块中处理 promise。 An example would be,一个例子是,


var model = newsapi.v2.everything({
    q: 'food and beverage',
    sources: '',
    domains: '',
    from: day_b4_yesterday,
    to: today,
    language: 'en',
    sortBy: 'relevancy',
    page: 2
}).then(response => {
    console.log(response);
    var NewsSchema = new Schema(response);
    return mongoose.model('News', NewsSchema);
});


module.exports = { model };

You can handle the resolution of this promise in the file or method which requires this.您可以在需要此的文件或方法中处理此 promise 的分辨率。 If interested in more asynchronous code look here at MDN web docs ,如果对更多异步代码感兴趣, 请查看 MDN web 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM