简体   繁体   中英

How to pass variable to an async function in another file called in Promise chain

How can I pass a variable to an async function in another file within a promise?

// file1.js

const thisFunc = require('./file2');
const foo = "bar";

const newPromise = new Promise((resolve, reject) => {
   thisFunc
       .asyncFunction() // <-- I want to pass foo here
       .then(...)
}
// file2.js

const asyncFunction = async () => {
 console.log(foo); // <-- and do stuff with foo here
}

module.exports.asyncFunction = asyncFunction

Pass the variable like you would any other - asynchronous activity doesn't prevent you from doing that:

thisFunc
    .asyncFunction(foo)
    .then(...)

Then add a parameter in asyncFunction :

const asyncFunction = async foo => {...};

the async function will not stop you for passing data to async function.

 // file2.js const asyncFunction = async (foo) => { console.log(foo); // <-- and do stuff with foo here } // file1.js // const thisFunc = require('./file2'); const foo = "bar"; const newPromise = new Promise((resolve, reject) => { // thisFunc. asyncFunction(foo) // <-- I want to pass foo here .then((data)=>{ console.log(data); resolve('From newPromise '); }) }); newPromise.then(console.log);

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