How can I export promise result?

前端 未结 4 1088
南笙
南笙 2021-01-07 23:12

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

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-08 00:01

    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.

提交回复
热议问题