简体   繁体   中英

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. 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 . But you are storing the response in window.feed . So you should store it in feed variable in the then block, That is the first thing.

You can assign it by using global or GLOBAL, nodejs supports both:

global.feed = response;

or

GLOBAL.feed = response;

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).

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. 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. If interested in more asynchronous code look here at MDN web docs ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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