0

This is for my vuejs+webpack project

How can i return a promise or wait for require to load a file ?

exmaple :

var myfile= require('./assets/myjson.json') // a big json file
console.log(myfile) //this sometime not printed correctly

sometime console.log not print object correctly in console

so i would like to know whether it is possible to return promise like this

require('./assets/myjson.json').then(function(){ 
   // big file loaded completetly
   console.log(myfile) 
}

i have to process the object after the require callback, i dont find a way to do this

the object is printed in console as below enter image description here

James Westgate
  • 11,306
  • 8
  • 61
  • 68
rashidnk
  • 4,096
  • 2
  • 22
  • 32

2 Answers2

1

You can do this:

1. Create a Promise

    var promise = new Promise(function (resolve, reject) {
        // do a thing, possibly async, then…

        if (/* everything turned out fine */) {
            resolve("Stuff worked!");
        }
        else {
            reject(Error("It broke"));
        }
    });

2. Using the Promise

    promise.then(function(result) {
       console.log(result); // "Stuff worked!"
    }, function(err) {
       console.log(err); // Error: "It broke"
    });

I hope be useful!

-1

Webpack is just node which means its just Javascript.

You can use the file API with a Promise API to achieve the desired result.

There is a ton of good info in this SO question.

Parse large JSON file in Nodejs

Sten Muchow
  • 6,623
  • 4
  • 36
  • 46