Sorry if this question is stupid.
This code works correctly. And I just need to export data variable after all promises successfully resolved.
I cannot put t
You should use promise function
promise.js
export function get_data(){
var get_data= new Promise(function(resolve, reject) {
//do your stuff
return resolve('success');
}).catch(function () {
return reject('err');
});
});
//return promise
return get_data;
}
Import
import * as data from './mypromise'
data.get_data().then((reuslt)=>{
console.log(result)})
Nowadays u do
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
async function foo() {
console.log('called')
await wait(1000)
return 'hi'
}
export default foo()
import foo from './foo'
void (async function() {
console.log(foo)
console.log(await foo)
console.log(await foo)
})()
> called
> Promise { <pending> }
> hi
> hi
It's usefull to fetch datas at start
You could easily assign it to an exported variable, but you should not do that - the assignment happens asynchronously, and the variable might be read before that in the modules where it is imported.
So instead, just export the promise1!
// data.js
import urls from './urls'
import getData from './get-data'
export default getData(urls).then(responses =>
responses.map(JSON.parse).map(magic)
);
// main.js
import dataPromise from './data'
dataPromise.then(data => {
console.log(data);
…
}, console.error);
1: Until the proposed top-level await comes along and you can just wait for the value before exporting it.
You can export your promise result by simply resolving the promise in the module from which to want to export, and in then() block use exports.variable_name = promiseResult;
For example: I want to use a database connection in my whole app. but the connect call return me a promise. so I can simply call the promise.then and i then block, export my desired result. Connection.js file
async function connect() {
connection = await oracledb.getConnection(config)
if (connection) {
return connection;
} else {
return null;
}
}
connect().then((res) => {
exports.connection = res;
});
then in main.js file, just simply require the connection.js file.
But this is not good practice because if your promise fails or take too much time to resolve, and it is used somewhere before it was resolved, may cause errors.