22

This code works correctly. And I just need to export data variable after all promises successfully resolved.

I cannot put this code to function and export variable. Because in this case, this function will export an empty array.

'use strict'

import urls from './urls'
import getData from './get-data'

getData(urls).then((responses) => {
    const data = []
    const results = responses.map(JSON.parse)

    for (let i = 0, max = results.length; i < max; i++) {
        // some magic and pushing 
    }

    return data
}).catch(error => console.log(error))
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Entry Guy
  • 425
  • 1
  • 7
  • 18
  • You don't, you use the call back `then`. That is when you have access to the data, you do not return it directly. Maybe I am not understanding what you mean by `need to export data variable after....` – Igor Mar 22 '17 at 17:11
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Mar 22 '17 at 17:16
  • See https://stackoverflow.com/questions/41279796/exporting-node-module-from-promise-result/41279904 – jchi2241 Jul 28 '18 at 18:16
  • Possible duplicate of [Exporting Node module from promise result](https://stackoverflow.com/questions/41279796/exporting-node-module-from-promise-result) – jchi2241 Jul 28 '18 at 18:16

4 Answers4

21

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
7

EDIT 2021

Node > 14.3

Since node now support top-level-await the solutions is extra basic

foo.js

export default await new Promise()

index.js

import foo from './foo.js' // the import wait for the promise to be resolved

console.log(foo) 

Below node 14.3

Nowadays u do

foo.js

const wait = ms => new Promise(resolve => setTimeout(resolve, ms))

async function foo() {
    console.log('called')
    await wait(1000)
    return 'hi'
}

export default foo()

index.js

import foo from './foo'

void (async function() {
    console.log(foo)
    console.log(await foo)
    console.log(await foo)
})()

output

> called
> Promise { <pending> }
> hi
> hi

It's usefull to fetch datas at start

Sceat
  • 1,427
  • 14
  • 12
0

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.

zubair Irfan
  • 103
  • 12
0

You should use Promise constructor with a custom

mypromise.js

export function get_data(){
  const get_data = new Promise(function(resolve, reject) {
    try {
      //do your stuff 
      return resolve('success'); // change this to whatever data your want
    } catch (err) {
      return reject(err);
    }
  });
  //return promise 
  return get_data;
}

Import

import * as data from './mypromise'

data.get_data()
  .then((result) => console.log(result))
  .catch((error) => console.error(error));
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
Balaji
  • 9,657
  • 5
  • 47
  • 47